gpt4 book ai didi

php - 如果不存在具有相同值的行,则插入该行

转载 作者:可可西里 更新时间:2023-11-01 07:58:13 25 4
gpt4 key购买 nike

我想在我的 MySQL 表 kh_comments 中插入一个新行,但只有当不存在具有相同值的行时才应该插入。

我是这样试过的,我知道这是完全错误的:

public function prepare($author, $arr) {
$conn = new mysqli($this->servername, $this->username, $this->password, $this->db_name);

foreach ($arr as $value) {

$stmt = $conn->prepare("INSERT INTO kh_comments WHERE NOT EXISTS (author, abstract) VALUES (?, ?)");
$stmt->bind_param("ss", $author, $value['id']);
$stmt->execute();

$stmt->close();
$conn->close();
}
}

我也尝试过使用 INSERT IGNORE INTO ... 但这对我也不起作用。

如有任何帮助,我们将不胜感激!

编辑:

这是我的表格的样子: enter image description here在我的 SQL 代码中,我没有定义 ID。那有必要吗?如果是这样,那么 SQL 会是什么样子?

最佳答案

Use INSERT IGNORE

If you use the IGNORE keyword, errors that occur while executing the INSERT statement are ignored. For example, without IGNORE, a row that duplicates an existing UNIQUE index or PRIMARY KEY value in the table causes a duplicate-key error and the statement is aborted. With IGNORE, the row is discarded and no error occurs. Ignored errors may generate warnings instead, although duplicate-key errors do not.

$stmt = $conn->prepare("INSERT IGNORE INTO kh_comments(author,abstract) VALUES (?, ?)");

$stmt->bind_param("ss", $author, $value['id']);
$stmt->execute();

$stmt->close();
$conn->close();

请注意,要使这种方法(或 REPLACE INTO 方法甚至 ON DUPLICATE KEY 方法)成功,您需要在不想重复的字段上有一个唯一索引。如上述文档摘录中所述

关于php - 如果不存在具有相同值的行,则插入该行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38500506/

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