gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:52:48 25 4
gpt4 key购买 nike

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

我如何制定一个查询,以便它可以:

1.能够输入姓名和金额

2.如果所述名称已经存在,它应该只通过将其值与从表单中获取的值相加来更新 money 列。尝试使用:

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

它满足第一个要求,但在更新 money 列时它只是用新值替换旧值,而不是添加它们。

完整代码(草稿版):

        <?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!");



}


?>

最佳答案

尝试insert ... on duplicate key update:

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

我假设你的变量 $name$amount 被正确转义了

关于php - 查询插入或如果需要更新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9753180/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com