我想在我的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 ……但这对我来说也没用.
任何帮助,将不胜感激!
编辑:
这是我的表格的样子:
在我的SQL代码中,我没有定义ID.那还需要吗?如果是这样,SQL将如何看待呢?
解决方法:
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方法),您需要在不希望重复的字段上使用唯一索引.正如上面文档中的摘录中提到的那样
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。