PDO:“无效参数号"(Invalid parameter number).当用相同的值替换多个参数时 [英] PDO: "Invalid parameter number" when substituting multiple parameters with same value
本文介绍了PDO:“无效参数号"(Invalid parameter number).当用相同的值替换多个参数时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果参数在查询中多次出现,如何绑定我的参数,如下所示?
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();
推荐答案
您为prepare语句提到了两个参数(具有相同的名称),但是仅为第一个参数提供了一个值(这就是错误所在)
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.
这篇关于PDO:“无效参数号"(Invalid parameter number).当用相同的值替换多个参数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文