尝试从时间戳开始按月计算

时间:2010-12-11 20:27:54

标签: php mysql date

我试图通过一个月的读数得到一个总和,并用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);                         
?>

4 个答案:

答案 0 :(得分:3)

当您应该使用=时,您的主要问题似乎是您正在使用==来测试相等性。除非您进行字符串比较并且数字带有前缀(例如0$foo == 1),否则不要在整数前加$foo == '01前缀。

如果直接插入数组,可以缩短它:

$readingarray[$month] += $row['readingVolume'];

另请注意,如果按月分组并执行SUM(),则可以通过MySQL执行此查询。如果你的领域是日期类型,那将是微不足道的。作为UNIX时间戳,您首先需要将其转换为日期。 (一个额外的MySQL函数调用。)

答案 1 :(得分:2)

假设readingDate在MySQL中是DATEDATETIME,您可能需要以下内容:

select SUM(readingVolume) as vol, MONTH(readingDate) from Reading order by readingDate group by MONTH(readingDate)

另外,正如konforce所指出的那样:你正在使用赋值运算符测试相等性。

此外,在PHP中,前缀为0的数字被解释为八进制,因此09实际上是== 0

取值

答案 2 :(得分:1)

这是一个与@konforce mentions in his answer相同的SQL:

SELECT SUM(readingVolume), FROM_UNIXTIME(readingDate, '%m') as m 
FROM Reading 
GROUP BY m

(更新:刚验证过可以在GROUP BY中使用别名)

答案 3 :(得分:0)

假设PHP的时间戳转换总是等于MySQL的时间戳是错误的。

你需要在MySQL工作。

SELECT SUM(readingVolume)as vol 从阅读 GROUP BY FROM_UNIXTIME(readingDate,'%m')