mysql_affected_rows() returns 0 for UPDATE statement even when an update actually happens
Posted
by
Alex Moore
on Stack Overflow
See other posts from Stack Overflow
or by Alex Moore
Published on 2012-02-22T15:03:56Z
Indexed on
2012/03/21
11:29 UTC
Read the original article
Hit count: 209
I am trying to get the number of rows affected in a simple mysql update query. However, when I run this code below, PHP's mysql_affected_rows() always equals 0. No matter if foo=1 already (in which case the function should correctly return 0, since no rows were changed), or if foo currently equals some other integer (in which case the function should return 1).
$updateQuery = "UPDATE myTable SET foo=1 WHERE bar=2";
mysql_query($updateQuery);
if (mysql_affected_rows() > 0) {
echo "affected!";
}
else {
echo "not affected"; // always prints not affected
}
The UPDATE statement itself works. The INT gets changed in my database. I have also double-checked that the database connection isn't being closed beforehand or anything funky. Keep in mind, mysql_affected_rows doesn't necessarily require you to pass a connection link identifier, though I've tried that too.
Details on the function: mysql_affected_rows
Any ideas?
SOLUTION
The part I didn't mention turned out to be the cause of my woes here. This PHP file was being called ten times consecutively in an AJAX call, though I was only looking at the value returned on the last call, ie. a big fat 0. My apologies!
© Stack Overflow or respective owner