php - 在 sql 中多次使用相同的准备语句参数

标签 php sql prepared-statement

我试图在我的 sql 中使用相同的参数,但它只识别第一个。看我的代码:

$stmt = $dbh->prepare("SELECT
    (SELECT SUM(oq.value)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user AND o.type = 1 AND oq.status = 1
    ) AS total_incomes_open,

    (SELECT SUM(oq.value)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user AND o.type = 1 AND oq.status = 2
    ) AS total_incomes_wroteoff");

$stmt->bindParam(":user", $this->getId());
$stmt->execute();

这可能吗?

最佳答案

像这样重用参数是不可能的。你必须制作独特的参数:

$stmt = $dbh->prepare("SELECT
    (SELECT SUM(oq.value)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user_a AND o.type = 1 AND oq.status = 1
    ) AS total_incomes_open,

    (SELECT COUNT(oq.id)
    FROM operations_quotas AS oq
        JOIN operations AS o ON oq.operation = o.id
    WHERE o.user = :user_b AND o.type = 1 AND oq.status = 2
    ) AS total_incomes_wroteoff");

$stmt->bindParam(":user_a", $this->getId());
$stmt->bindParam(":user_b", $this->getId());
$stmt->execute();

来自Manual :

You must include a unique parameter marker for each value you wish to pass in to the statement when you call PDOStatement::execute(). You cannot use a named parameter marker of the same name twice in a prepared statement. You cannot bind multiple values to a single named parameter in, for example, the IN() clause of an SQL statement.

关于php - 在 sql 中多次使用相同的准备语句参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13586012/

相关文章:

php - Mysqli INSERT 未显示在数据库中且没有错误

sql - ASP 更新数据库,如果不存在则插入

php - 如何使用命令提示符 : error 连接到 mysql 服务器

php - 准备好的语句。执行后绑定(bind)是否正确?

当字段有空格时 MySQL 准备好的语句不起作用

PHP MYSQL INSERT 不再有效

php - 既然 preg_match 函数似乎支持递归,是否可以使用它来解析 HTML?

javascript - 我有同名的表格

提取部分列的SQL查询

php - 如何在存储过程中使用 MySQLi 准备语句