【发布时间】:2015-07-04 03:29:39
【问题描述】:
如果在这种情况下存在其他插入,则 UPDATE 的正确格式是什么 - 我已设法分别进行更新和插入,但需要将它们放在一起?
我想要的是 - 如果日期存在,则更新为全天,如果不存在,则插入包含新详细信息的新行。
$date = (isset($_POST['date']) ? $_POST['date'] : null);
$reservationType = (isset($_POST['reservation-type']) ? $_POST['reservation-type'] : null);
$connect = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($connect->connect_error) {
die("connection failed: ". $connect->connect_error);
}
$sql = "SELECT * FROM reservations";
$result = $connect->query($sql);
if ($result -> num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($date == $row['date_of_reservation']) {
"UPDATE reservations SET reservationType = 'FULLDAY' WHERE date_of_reservation='$date'";
}
else {
"INSERT INTO reservations (date_of_reservation, reservationType) VALUES ('$date', '$reservationType')";
}
}
}
【问题讨论】:
-
那么给定的代码到底有什么问题?
-
INSERT ... ON DUPLICATE KEY UPDATE->If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row is performed. -
问题是给定的代码不起作用 - 因为数据库没有任何反应
-
您没有进行查询,您只是定义了 2 个查询字符串。您需要对这些字符串执行
$connect->query()。