我想按当前日期计算来自不同表的记录,并作为新表中具有不同列的一行返回。该代码将每三个小时更新一次记录,并在当前日期更改时插入新记录。我在“ created_at”列中拥有当前日期和时间数据(2013-05-20 14:12:12)。这是我当前的代码:

require_once('./db_connect.php');
$dbcon = new db;

//test to see if a specific field value is already in the DB
public function in_table($table,$where) {
  $query = 'SELECT * FROM ' . $table . ' WHERE ' . $where;
  $result = mysqli_query($this->dbh,$query);
  $this->error_test('in_table',$query);
  return mysqli_num_rows($result) > 0;
}

//running in background
while (true) {
   $select= "SELECT (SELECT CURDATE()) AS time," .
           "(SELECT COUNT(tweet_id) FROM tweets WHERE created_at= 'CURDATE() %') AS total_count," .
           "(SELECT COUNT(fid) FROM fun WHERE ftime= 'CURDATE() %') AS f_count," .
           "(SELECT COUNT(sid) FROM sad WHERE stime= 'CURDATE() %') AS s_count";

    $results = mysqli_query( $dbcon, $select );

    while($row = mysqli_fetch_assoc($result)) {
       $time = $row['time'];
       $total = $row['total_count'];
       $fcount = $row['f_count'];
       $scount = $row['s_count'];

       $field_values = 'time = "' . $time . '", ' . 'total_count = ' . $total . ', ' . 'fun_count = ' . $fcount . ', ' . 'sad_count = ' . $scount;

       if ($dbcon->in_table('count','time= "' . $time . '"')) {
         $update = "UPDATE count SET $field_values WHEN time= '$time'";
         mysqli_query( $dbcon, $update );
       }
       else {
         $insert = "INSERT INTO count SET $field_values";
         mysqli_query( $dbcon, $insert );
       }
   }

   //update record every 3 hour
   sleep(10800);
}


使用此代码,我无法获得计数记录。结果返回| 2013-05-18 | 0 | 0 | 0 |。我该如何纠正?

最佳答案

更换零件所在的位置:

WHERE created_at= 'CURDATE() %'


有了这个:

WHERE DATE(created_at) = CURDATE()


您现有的WHERE子句会将created_at与字符串常量CURDATE() %进行比较,并且它们将永远不匹配。

10-07 19:37
查看更多