A CakePHP SQL UPDATE example

CakePHP SQL UPDATE FAQ: How do I perform a SQL UPDATE with CakePHP?

As I was writing a user registration process for a CakePHP application, I just found myself in a situation where I needed to write a CakePHP SQL UPDATE query. While you don't pay attention to it, you often run a SQL UPDATE query in CakePHP in a typical controller edit() function, but this was the first time I really had to do this manually.

The short answer is that you execute a SQL UPDATE query in CakePHP using the usual model save() method. The way the save method work is like this:

  1. If the 'id' field IS NOT set, CakePHP executes a SQL INSERT query.
  2. If the 'id' field IS set, CakePHP executes a SQL UPDATE query.

So, the key to running a CakePHP SQL UPDATE query is to make sure the id field for your data is set.

A CakePHP SQL UPDATE example

Here's some CakePHP source code to demonstrate this. I've added comments to the code to describe what it's doing, so I won't say much else about it here, other than I use this code during the user registration process for a CakePHP website:

# first save the initial user data from the registration form
$this->User->create();
if($this->User->save($this->data))
{
  # come here when the save succeeds. 
  # now create a 'secret', email the secret to the user,
  # and update the user's record in the database
  
  # (1) get the secret
  $secret = $this->User->create_secret();
  $this->data['User']['registration_secret'] = $secret;

  # (2) send the email
  $this->send_registration_email($this->data['User']['registration_secret']);
  
  # (3) set the time the email was sent
  $sql_date = date("Y-m-d H:m:s");
  $this->data['User']['email_sent_time'] = $sql_date;

  # here's where the cakephp sql update happens:
  $this->User->save($this->data);
}

Because I'm manually adding data to the "$this->data['User']" array, and because the 'id' field in this array is already set (it was set when I executed the first save() at the top of the code listing), the second save() call at the bottom of the listing runs a CakePHP SQL UPDATE instead of a CakePHP SQL INSERT.

CakePHP SQL UPDATE - Summary

I can add more to this CakePHP SQL UPDATE tip if you'd like, but until there are any questions or comments I'll leave it like this. For more information, check out the Saving Your Data section of the CakePHP Cookbook.