逐行输出SQL查询JSON

时间:2015-02-20 10:02:06

标签: php mysql json count grouping

我的SQL查询是选择日期和进行计数,以及按日期分组。

我不知道如何逐行输出JSON输出。

 $sql = "SELECT DATE(timestamp), COUNT(eventid)
 FROM `tablex`
 WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
 GROUP BY DATE(timestamp) ";

 $stream = mysqli_query($conn, $sql);


if (mysqli_num_rows($stream) > 0) {

   while($row = mysqli_fetch_assoc($stream)) {

     // Is this where I should echo JSON? 
     // The problem is I'm not retrieving records but count and doing
     // a grouping

     }}

3 个答案:

答案 0 :(得分:0)

使用mysqli_fetch_array(),同时使用mysql_num_rows()计算:

$sql = "SELECT DATE(timestamp), COUNT(eventid)
 FROM `tablex`
 WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
 GROUP BY DATE(timestamp) ";

 $stream = mysqli_query($conn, $sql);

if (mysqli_num_rows($stream) > 0) {
   $rowCount = mysql_num_rows($result);
   while($row = mysqli_fetch_array($result, MYSQLI_NUM)){
       // Process JSON here use $row[0], $row[1], and so
   }
}

答案 1 :(得分:0)

无论您希望以JSON字符串形式返回什么,都应该始终将数据写入单个数组,然后使用名为json_encode()的这个很好的小PHP函数。例如:

$sql = "SELECT
   DATE(timestamp) as date_timestamp,
   COUNT(eventid) as count_eventid
   FROM `tablex`
   WHERE timestamp >= date_sub(CURRENT_DATE, interval 30 day)
   GROUP BY DATE(timestamp);";

$stream = mysqli_query($conn, $sql);

// prepare return array
$mydata = array(
    'eventcount' => 0
);

if (mysqli_num_rows($stream) > 0) {
    while($row = mysqli_fetch_assoc($stream)) {
        // just collect your data here, do not JSONify here
        $mydata['eventcount'] += $row['count_eventid'];
    }
}
// We got all our data, so return JSON encoded array
echo json_encode($mydata);

你会得到像

这样的东西
{"eventcount":"1234"}

答案 2 :(得分:0)

我设法得到一个输出:

$stream = mysqli_query($conn, $sql);

$lines = array();
while($line = mysqli_fetch_assoc($stream)) {
      $llines[] = $line;
}

print json_encode($lines);