Tuesday, February 17, 2009

How to update a single field in CakePHP

Here's a quick line of code to demonstrate how to update a single field in CakePHP.

Suppose we will be updating a field named 'confirmed' in a model called 'User' with the id of 5. We will then have an array with just that value, like this:

$data = array(
'User' => array(
'id' => 5,
'confirmed' => 1

We should then pass it on to a save function:

$this->User->save( $data, false, array('confirmed') );

You can RTFM about the save() function here.


Anonymous said...

You've got some nice tutorials and lessons looking forward for the next post ;P

tomotomo said...

Nice :)
This code does not update `modified` field

Anonymous said...

This does not update a field, it creates a new one, why is it that all searches on updating a field in cakephp lead to posts about how to create new fields.

Anonymous said...

The heading how to update single field in cakephp

Rupak 4 u said...

not working..

Anonymous said...

thanks mate , working fine chaeers

Anonymous said...

Those of you saying it's not working.
Do you remember to set the ID ?

Mareg said...

Add to Your AppModel in app directory.

* Set value just for one field in TB
* @param int $vNnId - cislo zaznamu
* @param string $sField - name of field
* @param mixed $sValue - value of field
function saveOneField($vNnId, $sField, $sValue) {
$sTable= $this->useTable;

return $this->query("UPDATE $sTable SET $sField = '$sValue' WHERE id = '$vNnId' LIMIT 1");

GoneShootin said...

//assuming $this->Post->id is set

$this->Post->saveField('title', 'A New Title for a New Day');