Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Update a field in Cakephp

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);
like image 400
hellosheikh Avatar asked Jun 26 '13 09:06

hellosheikh


People also ask

How to update data in CakePHP?

To update a record in database, we first need to get hold of a table using TableRegistry class. We can fetch the instance out of registry using the get() method. The get() method will take the name of the database table as an argument. Now, this new instance is used to get particular record that we want to update.

How can I print query in cakephp 2?

Add below code in app_model. php file which is located at root/cake/libs/model. Add below line in your model where you want print query. $last_query = $ this ->ModelName->getLastQuery();


1 Answers

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.

like image 116
AD7six Avatar answered Nov 15 '22 09:11

AD7six