how to Update a field in Cakephp

hellosheikh picture hellosheikh · Jun 26, 2013 · Viewed 31.7k times · Source

i am newbie in Cakephp so I feel difficulties to implement the database queries .. what i want is I want to update a mobile Number where email is equal to the one the user has given .. this is the query which i want to implement

        "Update Users set  mobileNo = $mobileNo  where email = $email"

I am doing this

      $mobileNo = $data['mobileNo'];
        $email = $data['$email'];


        $count = $this->User->find('count', array(
            'conditions' => array('User.email' => $email)));

        if($count>0){

            $email = $this->User->field(
                'email',
                array('User.mobileNo' => $mobileNo));
            echo $email;

            $this->User->saveField("mobileNo",$mobileNo);

Answer

AD7six picture AD7six · Jun 26, 2013

Updates in CakePHP are normally all based around knowing the primary key of the records you want to edit.

Normal/Simple

An example of updating a single field would be:

$this->User->id = $this->User->field('id', array('email' => $email));
if ($this->User->id) {
    $this->User->saveField('mobileNo', $mobileNo);
}

This would result in the following queries (some counts omitted):

SELECT id from users where email = "$email"
UPDATE users set mobileNo = "$mobileNo" where id = <id>

Atomic

You can however perform exactly the same query as appears in the question using updateAll:

$this->User->updateAll(
    array('mobileNo' => "'$MobileNo'"),
    array('email' => $email)
);

This would result in the following queries:

UPDATE users set mobileNo = "$mobileNo" where email = "$email"

If you use updateAll pay attention that the update is expected to be sql fragments - that means you need to quote strings.