【问题标题】:using same prepared statement parameter multiple times in a sql在 sql 中多次使用相同的预处理语句参数
【发布时间】:2012-11-27 14:08:04
【问题描述】:

我试图在我的 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();

这可能吗?

【问题讨论】:

  • 不,您必须将其作为不同的参数提供(它们必须是唯一的),然后单独绑定它们。

标签: php sql prepared-statement


【解决方案1】:

不能重复使用这样的参数。您必须制作独特的参数:

$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

当您调用 PDOStatement::execute() 时,您必须为希望传递给语句的每个值包含一个唯一的参数标记。您不能在准备好的语句中两次使用同名的命名参数标记。您不能将多个值绑定到单个命名参数,例如 SQL 语句的 IN() 子句。

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 2014-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多