PDO fetchAll以不同于SQL请求的数组输出

时间:2017-07-30 12:03:42

标签: php sql pdo

我有MySQL DB,它每分钟存储数据(对于日期1.7.2017我有1012个值为1):

id| value |timeDate
1 | 1     |2017-07-01 ...
2 | 0     |2017-07-01 ...
3 | 1     |2017-07-01 ...
.....

我想每天计算值为1(函数)的值:

$stmt = $db->prepare("SELECT day(dTimeDate), COUNT(*) FROM sensorData
        WHERE MONTH(dTimeDate) = :dateMonth AND YEAR(dTimeDate) = :dateYear AND _idSensor = :idSensor AND dValue = :valueSensor
        GROUP BY dTimeDate");
$stmt->execute(array(':dateMonth' => $m, ':dateYear' => $y, ':idSensor' => $idSensor, ':valueSensor' => $valueSensor));
$row2 =$stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($row2 as $row) {
    echo $row['day(dTimeDate)']. ' - ' .$row['COUNT(*)'].'<br/>';
}

我希望得到(就像我的SQL,example):

(day | Count)
1 - 1012 (count all values with value 1 in day 1)
2 - 105
...(31 lines, one for every day)

相反,我得到:

(day | Count)
1 - 1
1 - 1
...(1012 lines of day 1 and value 1)
2 - 1

row2返回所有数据的数组,而不是每天。

我如何获得预期值?

1 个答案:

答案 0 :(得分:1)

代码中有一点错误: -

group by dTimeDate更改为group by day(dTimeDate)

更正完整代码

$stmt = $db->prepare("SELECT day(dTimeDate), COUNT(*) FROM sensorData
    WHERE MONTH(dTimeDate) = :dateMonth AND YEAR(dTimeDate) = :dateYear AND _idSensor = :idSensor AND dValue = :valueSensor
    GROUP BY day(dTimeDate)");

$stmt->execute(array(':dateMonth' => $m, ':dateYear' => $y, ':idSensor' => $idSensor, ':valueSensor' => $valueSensor));
$row2 =$stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($row2 as $row) {
    echo $row['day(dTimeDate)']. ' - ' .$row['COUNT(*)'].'<br/>';
}