help please subtraction code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
reecec
Forum Contributor
Posts: 218
Joined: Sun Apr 02, 2006 7:12 am

help please subtraction code

Post 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
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post 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.
GM
Forum Contributor
Posts: 365
Joined: Wed Apr 26, 2006 4:19 am
Location: Italy

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
reecec
Forum Contributor
Posts: 218
Joined: Sun Apr 02, 2006 7:12 am

hi

Post by reecec »

Thanks GM


thats perfect sorry for the lack of detail


thanks to all others too

Reece
Post Reply