我有一个简单的php文件,可以为数据库添加id和时间。如果“id”与数据库中已存在的id相同,并且如果id已经不在数据库中,那么我如何将其更改为仅更新“time”?我遇到了'INSERT ... ON DUPLICATE KEY UPDATE'语法,但无法正确实现它。任何帮助,将不胜感激。谢谢!
<?php
$host="localhost";
$username="*****";
$password="*****";
$db_name="*****";
$id = htmlspecialchars($_GET["id"]);
$time = intval(htmlspecialchars($_GET["time"]));
echo $id;
echo $time;
$data = array("id" => $id, "time" => $time);
var_dump($data);
$mysqli = new mysqli($host, $username, $password, $db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("INSERT INTO testdata (id, time) VALUES (?, ?)");
if($stmt === FALSE)
die("Prepare failed... ");// Handle Error Here
// the types of the data we are about to insert: s = string, i = int
$stmt->bind_param('si', $data['id'], $data['time']);
$stmt->execute();
$stmt->close();
// close the connection to the database
$mysqli->close();
?>
答案 0 :(得分:0)
您应该执行以下操作:
INSERT INTO testdata (id,time) VALUES(?,?)
ON DUPLICATE KEY UPDATE time=values(time)
但正如@Mike W在评论中所说,确保ID是主键或唯一INDEX。 docs
中的更多信息