在sql中多次使用相同的预处理语句参数

leo*_*oap 3 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();
Run Code Online (Sandbox Code Playgroud)

那可能吗?

MrC*_*ode 5

重用这样的参数是不可能的.你必须做出独特的参数:

$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();
Run Code Online (Sandbox Code Playgroud)

手册:

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