问题
I have a query that looks like this:
SELECT CONCAT('path/to/page/?id=', id) AS link FROM users WHERE name = ?
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
because it thinks the question mark in the CONCAT string is a placeholder.
Is there any way to escape the question mark so PDO knows that it is not a placeholder?
Please no comments about other ways to get the link. I am changing old code that goes into an old templating engine so it would be A LOT less work to find a way to escape the question mark than to not put a question mark in the query.
回答1:
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());
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.
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()).
来源:https://stackoverflow.com/questions/25490170/php-pdo-escape-question-mark-so-it-doesnt-think-it-is-a-placeholder