我有一个名为
的表用户代码,id自动递增
id|user|code|quantity
目前我正在插入这样的新字段。
$query= "INSERT INTO usercodes (user,code,quantity) values
('".$user."',(SELECT code FROM promocodes WHERE id = '".$id."'),
'".$quantity."' )";
假设有一个现有条目。
id|user|code|quantity
1|john|code1|1
如果名为 john 的用户已有 code1 代码,我该如何更新数量而不是插入另一行?
预期结果
id|user|code|quantity
1|john|code1|2
而不是
id|user|code|quantity
1|john|code1|1
2|john|code1|1
最佳答案
很简单,您需要检查数据是否已存在于表中,因此首先尝试选择查询。
我假设用户和代码对于所有用户来说都是唯一的,因此:
第 1 步:使用用户和代码值运行选择查询,并检查表中是否存在具有相同详细信息的数据。
第 2 步 a:检查行数,如果为 1,则您拥有数据,这里获取该行的数量,从中添加/减去数量值,然后运行 UPDATE 查询。
步骤2 b:检查行数,如果为0则表示没有数据,这里运行INSERT查询。
$Query = "SELECT * FROM usercodes WHERE user = ? AND code = ? LIMIT 1";
$user = "USERVALUE";
$code = "CODEVALUE";
$stmt = $conn->prepare($Query);
$stmt->bind_param("ss", $user, $code);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0){
while($row = $result->fetch_assoc()) {
//Here get the quantity and add the amount u want to add in it and run the update query
}
}else{
//Store data as new record
}
关于php - 如果字段存在则更新数量,如果不存在则插入新条目 mysql php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54275520/