PDO:“无效的参数号"用相同的值替换多个参数时
如果我的参数在查询中多次出现,我该如何绑定,如下所示?
How do I bind my parameter if it appears multiple times in the query as follows?
$STH = $DBH->prepare("SELECT * FROM $table WHERE firstname LIKE :string OR lastname LIKE :string");
$STH->bindValue(':string', '%'.$string.'%', PDO::PARAM_STR);
$result = $STH->execute();
推荐答案
您提到了准备语句的两个参数(同名),但您只为第一个参数提供了一个值(这就是错误所在).
You mentioned two parameters (with the same name) for the prepare statement, yet you supply a value for the first parameter only (that's what the error was about).
不太清楚 PDO 如何在内部解决相同参数名称的问题,但您总是可以避免这种情况.
Not quite sure how PDO internally solved the same-parameter-name issue, but you can always avoid that.
两种可能的解决方案:
$sql = "select * from $table ".
"where "
"first_name like concat('%', :fname, '%') or ".
"last_name like concat('%', :lname, '%')";
$stmt= $DBH->prepare($sql);
$stmt->bindValue(':fname', $string, PDO::PARAM_STR);
$stmt->bindValue(':lname', $string, PDO::PARAM_STR);
<小时>
$sql = "select * from $table ".
"where "
"first_name like concat('%', ?, '%') or ".
"last_name like concat('%', ?, '%')";
$stmt= $DBH->prepare($sql);
$stmt->bindValue(1, $string, PDO::PARAM_STR);
$stmt->bindValue(2, $string, PDO::PARAM_STR);
<小时>
顺便说一下,您现有的方式仍然存在 SQL 注入问题.
By the way, the existing way you have done still has SQL injection issues.
相关文章