views:

33

answers:

3

Hi all,

I am using cakePHP 1.26.
I was trying to update a Table using these lines of code:

$c = "helloworld";
$q="UPDATE user SET avatar='{$c}' WHERE user_id='999999'";
$result=$this->Test->User->query($q);

if($result==true){echo "success";}
else{echo "failed";}

I noticed that the Table was updated successfully, but I still saw the "failed" message.
It seems that the value of $result is neither True nor False.

I have no idea.

+1  A: 

An update query on SQL returns number of rows updated. So it might be returning an integer not bool.

Ankit Jain
+2  A: 

query() returns the result set from the SQL query. You won't get a success vs. failure result. That said, you probably shouldn't be using query() anyway. There's a function for this; it's called saveField() and it returns false on failure.

$this->Test->User->id = 999999;
$result = $this->Test->User->saveField('avatar', $c);
if ($result !== false) echo "success";
else echo "failed";

If you insist on using query() there's no reason to go to another model. It just executes an SQL query. This would work as well as what you wrote:

$this->query($q);

Incidentally, if ($result == true) is redundant and generally considered poor form. just if ($result) will work identically.

macamatic
You probably mean `$this->Test->User->saveField()`... Regardless, solid answer. There's no reason not to use Cake's ORM here.
deceze
That helps. Thank you, macamatic.
D'oh! You're right, I meant `$this->Test->User->saveField`. Editing now.
macamatic
+1  A: 

after the table is updates it returns the affected rows numbers. so after your query finished if you would call this function "mysql_affected_rows" you would get the affected rows,and if it is greater than 0 that means the query excecuted succesfully and if it is 0 then the update is not done ..

dip1232001
oops ! you are using cakephp .here is the query how it should be done $c = "helloworld";$q="UPDATE user SET avatar='{$c}' WHERE user_id='999999'";if($this->Test->User->query($q))echo "success";}else{echo "failed";}################################for note it returns you the id of the row which is being updated you can get it by$this->Test->User->id
dip1232001
and for your information,i am assuming that user_id is the primary key in your table user,but as you are using cakephp you should name all primary keys as idthen you can write that query like this $this->Test->User->id=99999;$this->Test->User->set('avatar', 'helloworld');if($this->Test->User->save()){echo 'success';}else{echo 'faliure';}
dip1232001
many thanks for the help, dip.