php - 尝试从时间戳按月汇总

标签 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);                         
?>

最佳答案

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

如果你直接插入你的数组,你可以让它更短:

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

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

关于php - 尝试从时间戳按月汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418788/

相关文章:

php - 在 Python 中获取 HTTP header

php - Zend_Db_Profiler_Firebug 获取 502 错误网关

php - Elasticsearch :使用通配符作为属性名称来映射属性类型

php - 我需要将 mysql 查询转换为 CakePHP 条件

java - 将 DateString 解析为 Date 或 DateTime

php - 单击元素时如何更新表格行+1?

mysql - 带有联合查询的下拉列表

Mysql 条件查询列出其中一个表中的列,但不列出两个表中的列

mysql - 按查询分组仅返回最新结果 - Codeigniter

java - 从 ISO 8601 日期字符串转换为 BigQuery 时间戳时出错