如何在 Doctrine prepared SQL 语句中使用 + 或 - 运算符作为参数?

How to use + or - operators as parameters in Doctrine prepared SQL statement?

正在尝试使用以下代码:

$operator = '+';
$conn = $entityManager->getConnection();
$stmt = $conn->prepare("
    UPDATE articles a SET a.position = a.position :operator 1
")->execute([
    'operator' => $operator
]);

在SQL语句UPDATE articles a SET a.position = a.position :operator 1中,:operator参数应替换为'+',来自先前定义的$operator变量,但实际上它运行 失败并且 returns 这个错误:

An exception occurred while executing 'UPDATE articles a SET a.position = a.position :operator + 1 with params ["+"]:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''+' 1

您不需要绑定您完全控制的文字字符。

并且绑定是针对实际参数的。保留字、运算符、数据库标识符……所有这些都不是"bound"到SQL语句中。由于这些永远不会来自用户输入,因此这样做毫无意义。

这只能通过现有配置、白名单字符串等安全地生成

正常插入连接字符串中的字符即可:

$operator = '+';
$conn = $entityManager->getConnection();
$stmt = $conn
    ->prepare("UPDATE articles a SET a.position = a.position $operator 1")
    ->execute();

因为你没有参数,你完全可以省去准备语句:

$stmt = $conn
    ->executeQuery("UPDATE articles a SET a.position = a.position $operator 1");