PDO => ' PDOException'消息' SQLSTATE [HY093]:参数号无效:参数未定义'

时间:2014-10-24 15:45:33

标签: php mysql pdo subquery

我正在尝试在我的PDO中运行子查询,但PDO不会拥有它。有什么建议?

带有消息'SQLSTATE [HY093]的未捕获异常'PDOException':参数号无效:参数未定义'

$userId = 1;
$promotionId = 1;

$sql = "
    SELECT 
        *, 
        ( 
            SELECT 
                COUNT(*) 
            FROM 
                promotion_user as spu 
            WHERE 
                spu.promotion_id = p.id AND 
                spu.user_id = :user_id 
        ) as num_uses 
    FROM 
        promotion as p 
    WHERE 
        p.id = :promotionId
";

//$db is the PDO connection
$getPromotions = $db->prepare($sql);
$getPromotions->bindValue(':user_id', $userId, PDO::PARAM_STR);
$getPromotions->bindValue(':promotion_id', $promotionId, PDO::PARAM_STR);
$getPromotions->execute();
$promotions = $getPromotions->fetchAll(PDO::FETCH_ASSOC);

1 个答案:

答案 0 :(得分:3)

在您的查询中写道:

:promotionId

当您绑定参数时,您写道:

$getPromotions->bindValue(':promotion_id', $promotionId, PDO::PARAM_STR);

你需要以相同的方式写,promotionId!= promotion_id。

所以你应该改变这一行:

p.id = :promotionId

对此:

p.id = :promotion_id