我正在尝试为我的数据库实现一个非常基本的搜索引擎,其中用户可能包含不同类型的信息。搜索本身由几个联合选择组成,结果总是合并到 3 列中。
然而,返回的数据是从不同的表中获取的。
每个查询都使用 $term 进行匹配,我将它绑定(bind)到 ":term"作为准备参数。
现在,手册说:
You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement.
我认为与其用 :termX (x for term = n++) 替换每个 :term 参数,还不如有更好的解决方案?
还是我只需要绑定(bind) X 个 :termX?
编辑发布我的解决方案:
$query = "SELECT ... FROM table WHERE name LIKE :term OR number LIKE :term";
$term = "hello world";
$termX = 0;
$query = preg_replace_callback("/\:term/", function ($matches) use (&$termX) { $termX++; return $matches[0] . ($termX - 1); }, $query);
$pdo->prepare($query);
for ($i = 0; $i < $termX; $i++)
$pdo->bindValue(":term$i", "%$term%", PDO::PARAM_STR);
好的,这是一个示例。 sqlfiddle 没时间,以后有需要我会加一个。
(
SELECT
t1.`name` AS resultText
FROM table1 AS t1
WHERE
t1.parent = :userID
AND
(
t1.`name` LIKE :term
OR
t1.`number` LIKE :term
AND
t1.`status` = :flagStatus
)
)
UNION
(
SELECT
t2.`name` AS resultText
FROM table2 AS t2
WHERE
t2.parent = :userParentID
AND
(
t2.`name` LIKE :term
OR
t2.`ticket` LIKE :term
AND
t1.`state` = :flagTicket
)
)
最佳答案
我现在已经多次遇到同样的问题,我认为我找到了一个非常简单且很好的解决方案。如果我想多次使用参数,我只需将它们存储到 MySQL User-Defined Variable
。
这使代码更具可读性,并且您不需要 PHP 中的任何其他函数:
$sql = "SET @term = :term";
try
{
$stmt = $dbh->prepare($sql);
$stmt->bindValue(":term", "%$term%", PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
// error handling
}
$sql = "SELECT ... FROM table WHERE name LIKE @term OR number LIKE @term";
try
{
$stmt = $dbh->prepare($sql);
$stmt->execute();
$stmt->fetchAll();
}
catch(PDOException $e)
{
//error handling
}
唯一的缺点可能是您需要执行额外的 MySQL 查询 - 但恕我直言,这是完全值得的。
由于 User-Defined Variables
在 MySQL 中是 session 绑定(bind)的,因此也无需担心变量 @term
在多用户环境中导致副作用。
关于php - 多次使用绑定(bind)参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18511645/