Justin
Justin

Reputation: 3

How do I apply a mathematical mysql query to each row in a database?

I am designing a database for an MMORPG, and the administrator back end. I need a function that will allow me to add a specified amount of the game's primary currency: Gold to each account in the database.

This is what I have:

function massAddGold($gold_amount){
    dbconnect();
    $value=mysql_query("SELECT * from `mmo_db1`.`users`;");
    while ($row=mysql_fetch_array($value)){
        $currentgold=$row['gold'];
        $newgold=$currentgold+$gold_amount;
        mysql_query("UPDATE  `mmo_db1`.`users` SET  `gold` =  \"$newgold\";");
    }
    dbclose();
}

where mmo_db1 is the name of the database.

When I execute the command, massAddGold("50"); I then check the database. It takes the row with the highest value of Gold, adds the 50 gold to that, then applies that value to all of the rows. I need it to execute on each row individually.

Upvotes: 0

Views: 460

Answers (3)

Fluffeh
Fluffeh

Reputation: 33512

Why do a select first? If you want to give everyone an extra 50 gold, why not do something like:

UPDATE  `mmo_db1`.`users` SET  `gold` =  `gold`+ $newgold;

Upvotes: 1

user557846
user557846

Reputation:

mysql_query("UPDATE mmo_db1.users SET gold = gold+50");

ps, mysql* =bad

Upvotes: 1

Adrian Cornish
Adrian Cornish

Reputation: 23866

Why do it in two queries what is wrong with one

UPDATE users SET  gold = gold + 50;

Upvotes: 5

Related Questions