Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php PDO:检查数据库中是否存在标签,然后插入_Php_Mysql_Tags_Pdo - Fatal编程技术网

Php PDO:检查数据库中是否存在标签,然后插入

Php PDO:检查数据库中是否存在标签,然后插入,php,mysql,tags,pdo,Php,Mysql,Tags,Pdo,我正在使用PDOconnection formysql,我想对一个用于检查数据库中是否存在标记的查询有一些看法,如果不存在,可以添加它 // the tags are allready processed in $tags array $check_stmt = $connection->prepare ("SELECT * FROM tags WHERE tag_name = :tag_name"); $save_stmt = $connection->prepare ("IN

我正在使用
PDO
connection for
mysql
,我想对一个用于检查数据库中是否存在
标记的查询有一些看法,如果不存在,可以添加它

// the tags are allready processed in $tags array 

$check_stmt = $connection->prepare ("SELECT * FROM tags WHERE tag_name = :tag_name");
$save_stmt = $connection->prepare ("INSERT INTO tags (tag_name) VALUES (:tag_name)");

foreach ($tags as $current_tag) {
    $check_stmt->bindParam (':tag_name', $current_tag, PDO::PARAM_STR, 32);
    $save_stmt->bindParam (':tag_name', $current_tag, PDO::PARAM_STR, 32);
    $check_stmt->execute ($current_tag);
    if ($check_stmt->rowCount() == 0) $save_stmt->execute ($current_tag);
}

我不熟悉数据库,因此我不确定查询是否得到了很好的预测

我会稍微调整您的选择查询,以优化:

SELECT 1 AS found FROM tags WHERE tag_name = :tag_name LIMIT 1
选择*会将更多数据(匹配记录中的所有字段)从数据库传输到应用程序,而不是必要的数据。只选择所需的字段效率更高,在本例中,看起来您只是在检查是否存在,因此不需要任何记录数据,因此选择1


限制1将查询结果限制为一条记录,而不是所有匹配的记录。更快的查询执行和更少的数据传输。

一些更脏的MySQL特定选项包括简单地使用REPLACE-INTO(不要)或IGNORE关键字与INSERT(建议)组合使用。INSERT IGNORE语法将比单独执行SELECT略快。

可能重复的