我正在使用 mysql
的 PDO
连接,我想对我用来检查 tags
的查询有一些意见> 存在于数据库中,如果不存在则添加它。
// 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
SELECTing * 会从数据库向您的应用传输多于必要的数据(匹配记录中的所有字段)。仅选择您需要的字段会更有效,在这种情况下,您看起来只是检查是否存在,因此您不需要任何记录数据,因此需要 SELECT 1。 p>
LIMIT 1 将查询结果限制为一条记录,而不是所有条匹配的记录。查询执行速度更快,数据传输更少。
关于php - PDO:检查数据库中的标签是否存在,然后插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2150312/