I have a personal project which is a browser based game, and I am currently working though old code, and trying to optimise and update everything. I have a lot of functions like the one below, which basically updates the players item amounts. When the item is used, the row is left in the db, but the amount is set to 0, then the amount is updated when the player buys/finds more of that item.
After searching on here I have an idea that something like 'update if exists' could work instead of using the COUNT query, and possibly a multi-query for the updates, but I am just not sure the best way to accomplish this, if possible.
The tables have an ID, which auto increments, but a player can have multiple rows in the tables, which I identify with userID.
I apologise if this is a newbish question, but I am self taught, and if you don't ask people who know what they are doing, you never learn the proper ways to do things :)
Also happy to get advice on the code in general.
function power_caps_to_loot($userID, $itemID, $amount, $itemName, $updateInv) {
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s
", mysqli_connect_error());
exit();
}
// check if user has any of items already
$query = "SELECT COUNT(itemID) from lootbag where userID = $userID AND itemID = $itemID";
$result = $mysqli->query($query);
$row = $result->fetch_array(MYSQLI_NUM);
$count = $row[0];
// if user has/had some already update amount, else insert new row
if ($count > 0) {
$query = "UPDATE lootbag SET amount = amount + $amount WHERE userID = $userID AND itemID = $itemID";
$mysqli->query($query);
} else {
$query = "INSERT INTO lootbag (itemID, userID, amount, itemName, type, sub_type)
VALUES ($itemID, $userID, $amount, '$itemName', 'Cyborg Power Capsule', 'cyb_power')";
$mysqli->query($query);
}
// if item comes from inventory, update amount
if ($updateInv == 1) {
$query = "UPDATE inventory SET amount = amount - $amount WHERE userID = $userID AND itemID = $itemID";
$mysqli->query($query);
}
$mysqli->close();
use on duplicate key update or "upsert"
insert into .... on duplicate key update col1 = values(col1) ...
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Set your indexs to not allow duplicates and that statement will handle the rest
INSERT INTO lootbag (itemID, userID, amount, itemName, type, sub_type)
VALUES ($itemID, $userID, $amount, '$itemName', 'Cyborg Power Capsule', 'cyb_power')
ON DUPLICATE KEY UPDATE amount = amount + values(amount)
should work, assuming you have a unique index on item ID and User ID