我想要有条件地更新和插入,但查询总是进行"插入"数据。否"更新"无论如何。我的代码如下:
<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";
}
?>
答案 0 :(得分:2)
问题是您正在检查表单提交,但也有else
语句,该语句将始终在页面加载时触发。您需要在表单提交检查中包装整个逻辑,然后检查id
参数。
// Form was submitted
if (isset($_POST['submit'])) {
if (!empty($_POST['id'])) {
// Update
} else {
// Insert
}
}