PHP PDO转义问号,因此它不认为它是一个占位符 [英] PHP PDO escape question mark so it doesn't think it is a placeholder

查看:139
本文介绍了PHP PDO转义问号,因此它不认为它是一个占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下查询:

SELECT CONCAT('path/to/page/?id=', id) AS link FROM users WHERE name = ?

我正在使用PDO编写此语句,但出现错误

I am using PDO to prepare this statement and I am getting the error

Invalid parameter number: number of bound variables does not match number of tokens

因为它认为CONCAT字符串中的问号是一个占位符.

because it thinks the question mark in the CONCAT string is a placeholder.

是否有任何方法可以使问号转义,所以PDO知道它不是占位符?

Is there any way to escape the question mark so PDO knows that it is not a placeholder?

请不要对获取链接的其他方式发表评论.我正在更改进入旧模板引擎的旧代码,因此与在查询中不添加问号相比,找到一种逃避问号的方法要少很多.

推荐答案

PDO不会与引号内的问号混淆.我只是用PHP 5.5.15对此进行了测试.

PDO is not confused by the question mark inside the quotes. I just test this with PHP 5.5.15.

$sql = "SELECT CONCAT('path/to/page/?id=', id) AS link FROM foo WHERE name = ?;";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(1, 'name');
$stmt->execute();
print_r($stmt->fetchAll());

它工作正常,没有错误的参数数量错误.您的错误是由绑定参数的方式引起的,而不是由SQL语法引起的.

It works fine, with no error about a wrong number of parameters. Your error is caused by the way you're binding parameters, not by the SQL syntax.

我怀疑您没有向我们显示整个SQL查询,因为没有FROM的WHERE无论如何都是语法错误.因此,您必须具有未显示给我们的其他参数占位符.如果您向我们展示了绑定参数(或将参数传递给execute())的方式,也会很有帮助.

I suspect you haven't shown us the whole SQL query, because WHERE without FROM is a syntax error anyway. So you must have additional parameter placeholders that you haven't shown us. It would also be helpful if you show us the way you're binding parameters (or passing parameters to execute()).

这篇关于PHP PDO转义问号,因此它不认为它是一个占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆