views:

33

answers:

3

So, this query:

mysql_query("UPDATE item SET name = 'foo' WHERE name = 'bar'");

is returning 1, but the value 'bar' doesn't exists in the table. As expected, nothing has changed in the database itself, but shouldn't mysql_query() return 0 in that case?

+3  A: 

It returns true, because the query was executed successfully. If you want to know how many rows were updated you have to use mysql_affected_rows.

captaintokyo
But shouldn't it fail, since the value it was supposed to find on the table doesn't exist?
David McDavidson
No, it's a valid query, so true is returned.
captaintokyo
`UPDATE ... WHERE` means "update any that exist," not "update and generate an error if none exist." Think of a `SELECT ... WHERE` that doesn't match any records: the query doesn't fail, it just found zero matching records.
Adam Backstrom
Yes, the query is valid. You are saying "update every row where name is foo to have the name bar." There are no columns named foo, so mysql happily does nothing. It will still check all the columns and see that none of the are named foo and continue -- perfectly normal behavior.
tandu
I see now, thanks for the replies
David McDavidson
+1  A: 

If you are just echoing the value of mysql_query, it would be true or false. You need to use mysql_affected_rows() to get the actual affected rows.

methodin
+1  A: 

Why, no. The query itself was successful, i.e. it was a valid query and was successfully executed. It just didn't apply to any row.

deceze