如果字段存在,则更新数量,如果不存在,则插入新条目php

时间:2019-01-20 10:27:47

标签: php mysql

我有一个名为

的表

用户代码,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 的用户已经具有代码1,我该如何更新数量而不是插入另一行?

预期结果

        id|user|code|quantity
        1|john|code1|2

代替

        id|user|code|quantity
        1|john|code1|1
        2|john|code1|1

2 个答案:

答案 0 :(得分:1)

很简单,您需要检查表中是否已存在数据,因此请首先尝试选择查询。

我认为用户和代码对于所有用户都是唯一的,所以:

步骤1:使用用户和代码值运行选择查询,并检查表中是否存在具有相同详细信息的数据。

步骤2 a:检查行数(如果为1),则说明有数据,这里获取该行的数量,从中减去/减去数量值,然后运行UPDATE查询。 / p>

步骤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 

    }

答案 1 :(得分:0)

使用INSERT ... ON DUPLICATE KEY UPDATE

  $query= "INSERT INTO usercodes (user,code,quantity) values 
  ('".$user."',(SELECT code FROM promocodes WHERE id = '".$id."'), 
  '".$quantity."' ) ON DUPLICATE KEY UPDATE quantity = quantity + 1";

确保您具有“用户”列的KEY,并将用户列设置为UNIQUE