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
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, ... ]

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.