douxiong4250 2017-03-11 11:46
浏览 15
已采纳

在更新之前检查列是否为零

How do i insert into a database checking if the column is zero before inserting into it

this is what i have tried but after updating it still insert a new row with the last inserted ID but rather i just want it to update without inserting

    $lastID = mysqli_insert_id($DBcon);
    $query2=$DBcon->query("SELECT * FROM mergeing"); 
    $compare_value = "0";
    if($row = $query2->fetch_array()) {
        $merger = "INSERT into mergeing(donator_1) VALUES ('$lastID')";
        if($row['donator_2'] !== "$compare_value") {
            if ($DBcon->query($merger)) {
                echo "success second";
            }
        }
    }
    while ($row = $query2->fetch_array()) {
        $idd= $row["_id"];
        $merg2 = "UPDATE mergeing SET donator_2='".$lastID."'  WHERE _id=$idd";
        if($row['donator_2'] === "$compare_value") {
            if ($DBcon->query($merg2)) {
                echo "success";
            }
        }
    } 
  • 写回答

1条回答 默认 最新

  • dongmuyan5638 2017-03-11 12:11
    关注

    It seems you want to check if there is a record that has a specific donator_2 value, and if so, you want it updated. If no such value is present, you want to insert a new record.

    Then your code could look like this:

    $lastID = mysqli_insert_id($DBcon);
    $compare_value = 0;
    $DBcon->query("UPDATE mergeing SET donator_2 = $lastID WHERE donator_2 = $compare_value");
    if ($DBcon->affected_rows) {
        echo "success: updated";
    } else {
        $DBcon->query("INSERT into mergeing(donator_1) VALUES ($lastID)");
        echo "success: inserted";
    }
    

    Depending on your actual use case, but you might want to also set the donator_2 value when you insert the new record.

    Please note that if the $compare_value is determined by user input or some other source that you cannot predict, then you should use prepared statements, as otherwise the code is open to SQL injection.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作