views:

97

answers:

2
mysql_query("update users set balance=balance+'$pwbalance'-'$totalprice' where memberid='$memberid' and (balance+'$pwbalance'-'$totalprice')>=0")or die(mysql_error());
$count=mysql_affected_rows();

When I echo $pwbalance, it is 40.00; when I echo $totalprice, it is 40; So there should be one record to be updated. However, when I echo $count, I get 0. What's wrong?

+6  A: 

MySQL only actually updates a row if there would be a noticeable difference before and after the updat. Your calculation is basically:

SET balance = balance + 40 - 40

So nothing changes, and MySQL will not count this as an affectd row.

Side note: don't single quote numeric values in the sql. single quotes act as string delimiters. For mysql , in this case, they are automatically converted to numbers, but it is bad practice at any rate.

Roland Bouman
I agree with Roland Bouman; if `$pwbalance` contains a value that is used as integer in the query, then don't use the quotes.
kiamlaluno
A: 

Roland is right, obviously you want to know if the query was successful, the fact that the balance stays the same is unimportant for you. You might want to add a new field like purchase_count that you increment in this update, or last_purchase_date, something to trigger an actual update.

MindStalker