我试图按月从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/