Jump to content

Update and Insert Question


Sinikka

Recommended Posts

What I'm trying to do is insert an item into the database if it doesn't exist but if it does exist I'm trying to get it to update the amount in stock. I have no problems getting it to insert if it doesn't exist but I can't get the existing stock to update. Here's the coding I'm working with.

 

if ($findItem[id])
{
$sql = mysql_query("SELECT * FROM admin_recieved WHERE item_id = '$findItem[id]' AND owner = '$findUser[id]'");
$result = mysql_num_rows($sql);

if($result =="0")
{
$sql = mysql_query("INSERT INTO admin_recieved (item_id,item_name,owner,owner_name,admin_id,admin_name,stock,date,game)
VALUES ('$findItem[id]','$findItem[item_name]','$findUser[id]','$findUser[display_name]','$userid','$username','$item_amount','$datestamp','$game')");

if($result != "0")
{ 
mysql_query("UPDATE admin_recieved SET stock = stock + $item_amount WHERE item_id = '$findItem[id]' AND owner = '$findUser[id]' AND game = '$game'");
        }
}
}

Link to comment
https://forums.phpfreaks.com/topic/96819-update-and-insert-question/
Share on other sites

You might want to take a look at the INSERT ... ON DUPLICATE KEY UPDATE... statement and get mysql to do this for you -

 

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [iGNORE]

    [iNTO] tbl_name [(col_name,...)]

    VALUES ({expr | DEFAULT},...),(...),...

    [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.