简体   繁体   English

无法使用bindValue,Postgresql在Doctrine DBAL中绑定字符串值

[英]Cannot bind string value in Doctrine DBAL using bindValue, Postgresql

I'm trying to use Doctrine DBAL in my project; 我正在尝试在我的项目中使用Doctrine DBAL; my database is Postgresql. 我的数据库是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 最好的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.) (顺便说一句,你应该真的使用模拟的预处理语句来做这样的事情。如果没有这样做,顺序by / limit子句基本上保证你最终会在整个地方进行seq扫描。)

Ok, I figured this out. 好的,我想通了。

Part of an SQL language cannot be used as a parameter in prepared statement. SQL语言的一部分不能用作预准备语句中的参数。 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... 我认为线程可以关闭......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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