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 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 ("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略快。可能重复的