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);
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.
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();
Updates in CakePHP are normally all based around knowing the primary key of the records you want to edit.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With