我正在尝试按月份从 mysql 中获取读数和文件的总和,日期在 sql 文件的日期时间戳字段中。
<?php
$db = new mysqli('localhost', 'php06', 'php06', 'php00');
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database. Please try again later.";
exit;}
$query = "select readingVolume, readingDate from Reading order by readingDate";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$mysqldate = $row['readingDate'];
$timestamp = strtotime($mysqldate);
$day = date("d", $timestamp);
$month = date("m", $timestamp);
$year = date("Y", $timestamp);
if ($month = 01){
$JanRead = ($row['readingVolume'] + $JanRead);}
if ($month = 02){
$FebRead = ($row['readingVolume'] + $FebRead);}
if ($month = 03){
$MarRead = ($row['readingVolume'] + $MarRead);}
if ($month = 04){
$AprRead = ($row['readingVolume'] + $AprRead);}
if ($month = 05){
$MayRead = ($row['readingVolume'] + $MayRead);}
if ($month = 06){
$JunRead = ($row['readingVolume'] + $JunRead);}
if ($month = 07){
$JulRead = ($row['readingVolume'] + $JulRead);}
if ($month = 08){
$AugRead = ($row['readingVolume'] + $AugRead);}
if ($month = 09){
$SepRead = ($row['readingVolume'] + $SepRead);}
if ($month = 10){
$OctRead = ($row['readingVolume'] + $OctRead);}
if ($month = 11){
$NovRead = ($row['readingVolume'] + $NovRead);}
if ($month = 12){
$DecRead = ($row['readingVolume'] + $DecRead);}
}
$readingarray = array($JanRead,$FebRead,$MarRead,$AprRead,$MayRead,
$JunRead,$JulRead,$AugRead,$SepRead,$OctRead,
$NovRead,$DecRead);
print_r($readingarray);
?>
最佳答案
您的主要问题似乎是您使用 =
来测试相等性,而您应该使用 ==
。并且不要在整数前加上 0
,除非您正在进行字符串比较并且数字有前缀(例如,$foo == 1
或 $foo == '01
).
如果你直接插入你的数组,你可以让它更短:
$readingarray[$month] += $row['readingVolume'];
另请注意,如果按月分组并执行 SUM()
,则可以通过 MySQL 执行此查询。如果您的字段是日期类型,那将是微不足道的。作为 UNIX 时间戳,您首先需要将其转换为日期。 (一个额外的 MySQL 函数调用。)
关于php - 尝试从时间戳按月汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418788/