如何使用mysql PDO和OR表达式计算字段数?

时间:2017-06-24 23:29:01

标签: php mysql pdo

无法计算结果数量来计算mySQL表中的字段(php / mysqlPDO)。

我遇到的挑战是,称为“轮换”的字段可以有许多值。我想将所有结果加在字段'rotation'中,对于一个名为“assignedRad”的特定用户,它等于29,30,31或32。

这是我的代码。错误是

  

参数号无效:绑定变量数与令牌数不匹配

$assignedRad=8; // this is the USER ID
// count vacation tally
$rotation=29;
$rotationoff=30;
$rotationvacay=31;
$rotationvacaytwo=32;                                       
$sql="SELECT COUNT(id) FROM my_table WHERE (rotation = :rotation OR rotation = :rotationoff OR rotation = :rotationvacay OR rotation = :rotationvacaytwo AND assignedRad = :assignedRad)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':rotation', $rotation);
$stmt->bindParam(':rotation', $rotationoff);
$stmt->bindParam(':rotation', $rotationvacay);
$stmt->bindParam(':rotation', $rotationvacaytwo);                                       
$stmt->bindParam(':assignedRad', $assignedRad);                                     
$stmt->execute();
$number_of_rows = $stmt->fetchColumn();
echo $number_of_rows;   // this value should be the SUM of the total number of times 'rotation' has an occurrence when it equals 29, 30, 31 or 32

SELECT语句显示字段数与变量数相同。 查询此代码最有效的方法是什么?

1 个答案:

答案 0 :(得分:1)

您没有在bindParam语句中使用正确的参数名称。它们必须匹配查询中使用的那些。

我认为你在设定OR之后错过了一个结束括号

$sql="SELECT COUNT(id) 
        FROM my_table 
        WHERE (    rotation = :rotation 
                OR rotation = :rotationoff 
                OR rotation = :rotationvacay 
                OR rotation = :rotationvacaytwo
            )
           AND assignedRad = :assignedRad";
$stmt = $dbh->prepare($sql);
$stmt->bindParam(':rotation', $rotation);
$stmt->bindParam(':rotationoff', $rotationoff);
$stmt->bindParam(':rotationvacay', $rotationvacay);
$stmt->bindParam(':rotationvacaytwo', $rotationvacaytwo);                                       
$stmt->bindParam(':assignedRad', $assignedRad);    

或者@ Chris85建议,稍微更改查询以使用IN子句

$sql="SELECT COUNT(id) 
        FROM my_table 
        WHERE rotation IN (:rotation,:rotationoff,:rotationvacay,:rotationvacaytwo)
           AND assignedRad = :assignedRad";

$stmt = $dbh->prepare($sql);
$stmt->bindParam(':rotation', $rotation);
$stmt->bindParam(':rotationoff', $rotationoff);
$stmt->bindParam(':rotationvacay', $rotationvacay);
$stmt->bindParam(':rotationvacaytwo', $rotationvacaytwo);                                       
$stmt->bindParam(':assignedRad', $assignedRad);