我想在我的 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 ...
但这对我也不起作用。
如有任何帮助,我们将不胜感激!
编辑:
最佳答案
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/