views:

81

answers:

1

I want to update a table:

$result=mysql_query("select balance from tablename where userid='$userid")or die(mysql_error());
$row=mysql_fetch_assoc($result);
$accountbalance=$row['balance'];
if($accountbalance>$cost)
{
$result=mysql_query("update tablename set balance-'$cost' where userid='$userid")or die(mysql_error());
}
else {
...
}

You see, I have to write two mysql statements, is there a better way to do it?

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();

Why is $count is 0 even I think it should be 1?

+3  A: 
UPDATE tablename SET balance=balance-$cost WHERE userid=$userid AND balance > $cost
Ben James
If you check that balance > cost I'd make damn sure that at least 1 row got updated. "Not enough balance, 0 rows updated' :-)
Khb
so I use mysql_affected_rows to get the result?
Steven
Right - I would just like to point out that in the answer, it should probably read "$cost" instead of just "cost" (in both cases without the double quotes)
Roland Bouman
Roland, you're right, I must have misread this as for some reason I had the idea that `cost` was another column. Fixed.
Ben James
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();Why is $count is 0 even I think it should be 1?
Steven