connect_error);-6ren">
gpt4 book ai didi

php - '成功'/'updated' 消息取决于操作

转载 作者:行者123 更新时间:2023-11-29 00:01:08 25 4
gpt4 key购买 nike

我有我的 sql 查询:

哎呀,你是对的。完整代码如下:

<?php
//variables here

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO Results (...)
VALUES (...)
ON DUPLICATE KEY UPDATE (...)";

if ($conn->query($sql) === TRUE) {
echo "Saved.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

如何在插入数据时显示消息“成功”或在更新数据时显示消息“已更新”?

最佳答案

根据manual您可以检测是否插入了一行或修改了一行:

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values.

我已在 PDO 中成功使用它,但我无法确认它在 msyqli 中是否也有效。不过,我很确定它会。

因此您必须检查 $conn->affected_rows 的返回值:

if ($conn->query($sql) === TRUE) {
if ($conn->affected_rows === 1) {
// new row inserted
} else {
// row found and possibly modified, you can filter for 0 or 2
// if you need more details.
}
} else {
...

关于php - '成功'/'updated' 消息取决于操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29780421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com