Page 1 of 1
help please subtraction code
Posted: Mon May 22, 2006 9:59 am
by reecec
hi i need some code for an online game
when something is purchased it deducts the money from there money row in the table
and if there is not enough money it gives a error
hope this isnt to hard thanks a lot
reece
Posted: Mon May 22, 2006 10:08 am
by RobertGonzalez
There are a couple of ways to do this. I would assume that you wouldn't want the user to be able to do something that requires money if they don't it, correct?
What I would do is select the user's financial's from the database. Check their current balance against the charge and see if it will be allowed. If it is not, error out. If it is, update the table to reflect the new account balance after the deduction.
Posted: Mon May 22, 2006 10:12 am
by GM
Um... it's a bit scarse in detail...
You are basically asking for code that does:
Code: Select all
$cost = 'cost of article purchased';
$availableCash = 'amount of money the user has';
if($cost > $availableCash) {
'throw error'
} else {
$moneyLeft = $availableCash - $cost;
$query = "UPDATE user_table SET cash=$moneyLeft WHERE id_user='$currentUser';
// do the query...
}
I can't be any more specific without knowing how your application handles the objects involved - personally I'd have a class for the thing being purchased, a class for the user, and I'd have a method in the article class ("buy" for example) that reduces the user's cash by the correct amount, while adding the object to the user's inventory.
Posted: Mon May 22, 2006 10:20 am
by feyd
I see this being easily done with a single UPDATE query and a call to
mysql_affected_rows() or a similar function of your specific database. No selection required.
hi
Posted: Mon May 22, 2006 10:46 am
by reecec
Thanks GM
thats perfect sorry for the lack of detail
thanks to all others too
Reece