我有一个简单的 php 文件,可以将 id 和时间添加到数据库中。如果“id”与数据库中已有的 id 相同,我如何将其更改为仅更新“时间”,如果 id 尚未在数据库中,则照常添加两者?我遇到了'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();
?>