0

I want to create a JSON table from the results of a SQL query. I tried the query on phpMyAdmin and it is correct (I get the data that I want) but then when I try to convert it to a JSON table using the code below, the result is a table with the correct structure but non of the values.

/* select all moches from the table moches */
$query="SELECT municipio, SUM(moche) AS moche FROM moches GROUP BY municipio";
$result = $mysqli->query($query);

     $rows = array();
     $table = array();
     $table['cols'] = array(

       array('label' => 'Municipio', 'type' => 'string'),           
       array('label' => 'Cantidad total en moches', 'type' => 'number')

                );

     foreach($result as $r) {

                      $temp = array();

                      //Create the different states

                      $temp[ ] = array('v' => (string) $r['municipio']); 

                      // Total de moches

                      $temp[ ] = array('v' => (int) $r['moche']); 
                      $rows[ ] = array('c' => $temp);


                    }

      $table['rows'] = $rows;

      // convert data into JSON format
      $jsonTable = json_encode($table);
4

2 回答 2

2

phpMyAdmin 允许以 JSON 格式导出,也许这可以帮助你。

于 2013-09-06T20:15:14.673 回答
1

nitpick:没有“json 表”之类的东西。有 JSON 字符串,它们是用其他语言(例如 javascript)表示数据结构的纯文本字符串。

你的问题是你试图循环一个 mysqli 结果句柄。这通常是单行数据,而不是整个结果集。

你应该有更多类似的东西:

$result = $mysqli->query($sql);

$temp = array();
while($row = $result->fetch_row()) {
    $temp[] = $row;
}
echo json_encode($temp);
于 2013-09-06T19:59:35.040 回答