如果我的参数在查询中多次出现,我该如何绑定,如下所示?
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.
这篇关于PDO:“无效的参数号"用相同的值替换多个参数时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
PHP、MySQL PDOException 的死锁异常代码?Deadlock exception code for PHP, MySQL PDOException?(PHP、MySQL PDOException 的死锁异常代码?)
PHP PDO MySQL 可滚动游标不起作用PHP PDO MySQL scrollable cursor doesn#39;t work(PHP PDO MySQL 可滚动游标不起作用)
PHP PDO ODBC 连接PHP PDO ODBC connection(PHP PDO ODBC 连接)
使用 PDO::FETCH_CLASS 和魔术方法Using PDO::FETCH_CLASS with Magic Methods(使用 PDO::FETCH_CLASS 和魔术方法)
php pdo 只从 mysql 获取一个值;等于变量的值php pdo get only one value from mysql; value that equals to variable(php pdo 只从 mysql 获取一个值;等于变量的值)
MSSQL PDO 找不到驱动程序MSSQL PDO could not find driver(MSSQL PDO 找不到驱动程序)