如何在不到六个月前的PHP和MySQL中查找行,按月

时间:2019-02-14 06:27:08

标签: php mysql loops

在phpmyadmin中执行时,我有以下SQL语句:

SELECT COUNT(cid) as total from courier where pick_date > DATE_SUB(now(),
INTERVAL 6 MONTH) group by year(pick_date), MONTH(pick_date)

结果:

COUNT(cid)

221
380
368
315
140
204
54

但是当我尝试使用PHP时,只能获得一个计数

$out = array();
$sql="SELECT COUNT(cid) as total from courier where pick_date > DATE_SUB(now(), INTERVAL 6 MONTH) group by year(pick_date), MONTH(pick_date)";
$pquery=$pdo->query($sql);
$prow=$pquery->fetch_all(PDO::FETCH_ASSOC);
$out[]=$prow['total'];
echo implode( ", ", $out );

实际结果:221

Expected:

221
380
368
315
140
204
54

预先感谢...:)

1 个答案:

答案 0 :(得分:2)

检查以下代码:

$out = array();
$sql="SELECT COUNT(cid) as total from courier where pick_date > DATE_SUB(now(), INTERVAL 6 MONTH) group by year(pick_date), MONTH(pick_date)";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC); 

$out = array();
foreach($stmt->fetchAll() as $value) {
    $out[] = $value['total'];
}
echo implode(", ", $out );

希望它对您有帮助。