简体   繁体   中英

Cannot bind string value in Doctrine DBAL using bindValue, Postgresql

I'm trying to use Doctrine DBAL in my project; my database is Postgresql. This is a simple use case and I really do not know why is this not working.

$query = "SELECT * FROM table ORDER BY field :order LIMIT :amount";

Let's assume that:

$order = 'DESC' and $amount = 'ALL';

The code above seems to be fine.

$statement = $app['db']->prepare($sql);
$statement->bindValue('order', $order);
$statement->bindValue('amount', $amount);
$statement->execute();

I get this error:

SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near "$1"
LINE 1: SELECT * FROM table ORDER BY field $1 LIMIT $2

Could someone explain this behaviour? I'm suspecting quoting problem...

Best Regrards
Kamil

Might you be missing a coma?

SELECT * FROM table ORDER BY field, :order LIMIT :amount

(Btw, you should really use emulated prepared statements for stuff like this. By not doing so, the order by/limit clauses basically guarantee that you'll end up with seq scans all over the place.)

Ok, I figured this out.

Part of an SQL language cannot be used as a parameter in prepared statement. So one should use some kind of conditional for example to create such query:

$sql = 'SELECT * FROM table ORDER BY field ';
if ($order = 'ASC') {
  $sql .= 'ASC ';
} else ... {
  ...
}
$sql .= 'LIMIT :amount';

Now everything should work.
And the parameter after the coma were treated as a parameter common to all queries and did not work. It could be everything and it had no impact on results.
I think the thread can be closed...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM