查询插入或如果需要更新记录

  +----------------+-----------+
  |name(varchar)PK |money(int) |
  +----------------+-----------+

How can i formulate a query so that it can:

1.Be able to insert a name and money value

2.If the said name already exists it should only update the money column by adding its value with that it gets from a form. tried using:

   REPLACE INTO practable SET name = '$name', money = 'money' + $amount

It fulfills the first requirement but while updating the money column it simply replaces the old value with the new one, doesn't add them.

Here is the full code(Draft version):

        <?php
           //This script by another form which takes the amount and name paramters from user
    if(!empty($_GET['nameg']) && !empty($_GET['amountg'])){

        $user="root";
        $pass="password";
        $db="practice";
        $name=$_GET['nameg'];
        $amount=$_GET['amountg'];

        mysql_connect('localhost',$user,$pass) or die("Connection Failed!, " . mysql_error());
        $query="REPLACE INTO practable SET name = '$name', given = 'given' + $amount";
        mysql_select_db($db) or die("Couldn't connect to Database, " . mysql_error());
        mysql_query($query) or die("Couldn't execute query! ". mysql_error());
        mysql_close() or die("Couldn't disconnect!");



    }


    ?>

Try insert ... on duplicate key update:

INSERT INTO practable(name,money) VALUES('$name',$amount) ON DUPLICATE KEY UPDATE
 name = '$name', money = `money` + $amount

I assume your variables $name and $amount are properly escaped

try leaving out the '' on money. That will keep it as a colmmn and not as a string

You're looking for the INSERT ... ON DUPLICATE UPDATE syntax.

From the documentation:

INSERT INTO table (a,b,c) VALUES (1,2,3)
    ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;

Try this:

$query="REPLACE INTO practable SET name = '$name', given = given+" . (int)$amount;

Replace will delete the old row if the primary key exists so you are adding to nothing.