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

标签 php mysql sql

我想在我的 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/

相关文章:

javascript - 为什么我们需要查询字符串?以及它到底是如何在后端使用来检索页面的?

MySQL 在具有多列/单列索引的范围查询上高效选择/排序

php - 如何以二进制形式获取 BIT(...) 数据类型列的值?

php - 如何在 php 中使用 memcache

php - 从 php 到 javascript 的 json 对象分配有什么问题?

通过Bash命令插入时Mysql不工作,但手动插入时工作

mysql - 我如何攻击这个 mySQL 查询?

sql - SSIS 无法读取 excel 文件中的列结尾(Excel 连接管理器)

python - 容差地从数据库中获取每n小时的数据

PHP 中类 Java 的集合