如果子句不给更新只工作插入。为什么更新不起作用?

时间:2018-05-24 13:36:23

标签: php mysqli

我想要有条件地更新和插入,但查询总是进行"插入"数据。否"更新"无论如何。我的代码如下:

<form method="post" action="">
    <label>ID: </label> <input type="text" name="id">
    <label>Subject: </label> <input type="text" name="subject">
    <input type="submit" name="submit">
</form>

<?php 
$conn = new mysqli("localhost", "root", "", "zidm"); 

$id=$_POST['id'];
$subject=$_POST['subject'];


if (isset($_POST['submit'])){
      $sql = "UPDATE exam  SET subject = '$subject'  WHERE id = '$id'";    
    mysqli_query($conn,$sql);
    echo "Data Updated";
  }
  else {
 $sql="INSERT INTO exam (subject) VALUES ( '$subject)";
    mysqli_query($conn,$sql);
    echo "Data Inserted";
  }

  ?>

1 个答案:

答案 0 :(得分:2)

问题是您正在检查表单提交,但也有else语句,该语句将始终在页面加载时触发。您需要在表单提交检查中包装整个逻辑,然后检查id参数。

// Form was submitted
if (isset($_POST['submit'])) {

    if (!empty($_POST['id'])) {
        // Update
    } else {
        // Insert
    }
}