...

View Full Version : subtract from mySQL data without negative number?



cyrus709
03-14-2009, 04:52 PM
I have a question

How can i subtract from a mysql DB, using php without allowing the number in the DB to go below '0'?
an example is
<?
$C = mysql_connect("host","user","pass");
if(!$C)
{
die();
}
mysql_select_db("database", $C);
mysql_query("UPDATE table SET col = col - 1");
?>
alright so the code works, but it can give me a negative number and i dont want to be able to have a negative number. im pretty sure that the code would be something like this?

<?
$C = mysql_connect("host","user","pass");
if(!$C)
{
die();
}
mysql_select_db("database", $C);
$var = mysql_query("UPDATE table SET col = col - 1");
if ($var < 0)
{
print "Cannot perform action";
}
?>
but that would not stop it i think instead of print it should be die() but that does not work either:confused::confused::confused::confused::confused:

tomws
03-14-2009, 05:24 PM
Your subject line is horrible. Help us help you. From http://www.codingforums.com/postguide.htm: "2) Type in a subject that summarizes your question- A great way to turn off other members wanting to help you is to type an incomplete or silly subject for your post."

Now, I think your update can be handled directly in SQL rather than PHP, but that assumes you don't want any feedback from the db on whether is was able to decrement and what the value is. If this is a real application, you probably want more information.

The direct SQL fix might look like this, but I'm not quite sure if it will work:

UPDATE table SET col = col - 1 WHERE col > 0;
You second code attempt won't work because you're mis-using the result from mysql_query. Read the man page (http://us3.php.net/mysql_query) to figure out what you're doing wrong.

abduraooft
03-14-2009, 05:27 PM
Your subject line is horrible.
Yes, one of the worst title I've ever seen here in this forum. Please edit your post and change that title.
Thanks

sea4me
03-14-2009, 11:12 PM
Yes, one of the worst title I've ever seen here in this forum. Please edit your post and change that title.
Thanks

I agree, change it to something like How to subtract from mySQL data without getting lower than one or something like that....



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum