【发布时间】:2016-02-06 02:16:51
【问题描述】:
我有一个代码,它运行查询并将其显示为页面上的表格,并在将查询转换为 json 变量之后立即显示。不幸的是,没有填充到 json 变量的转换,当我打印 json 变量时,我只收到没有数据的列名。
这是我的代码:
<?php
if (isset($_GET['variable'])) {
$_SESSION['variable'] = $_GET['variable'];
$results = mysqli_query($mysqli,"select q1.variable, t3.label, q1.numvalue, description, num_cases from (select variable, numvalue, count(variable) as num_cases from nhws.num_all_{$_SESSION['country']} where variable = '{$_SESSION['variable']}' group by variable, numvalue) q1 inner join (select * from nhws.luvalues where source = '{$_SESSION['country']}' and variable = '{$_SESSION['variable']}') t2 on q1.numvalue=t2.numvalue inner join (select * from nhws.luvariables where source = '{$_SESSION['country']}' and variable = '{$_SESSION['variable']}') t3 on q1.variable=t3.variable;");
echo "<h5>Counts</h5>";
if ($results->num_rows > 0) {
echo "<table><tr><th>Variable</th><th>label</th><th>Numvalue</th><th>Description</th><th>Num Cases</th></tr>";
// output data of each row
while($row = $results->fetch_assoc()) {
echo "<tr><td>" . $row["variable"]. "</td><td>" . $row["label"]. "</td><td>" . $row["numvalue"]. "</td><td>" . $row["description"]. "</td><td>" . $row["num_cases"]. "</td></tr>";
}
echo "</table>";
} else {echo "0 results";}
$rows = array();
//flag is not needed
$flag = true;
$table = array();
$table['cols'] = array(
// Labels for your chart, these represent the column titles
// Note that one column is in "string" format and another one is in "number" format as pie chart only required "numbers" for calculating percentage and string will be used for column title
array('label' => 'variable', 'type' => 'string'),
array('label' => 'num_cases', 'type' => 'number')
);
$rows = array();
while($r = $results->fetch_assoc()) {
$temp = array();
// the following line will be used to slice the Pie chart
$temp[] = array('v' => (string) $r["variable"]);
// Values of each slice
$temp[] = array('v' => (int) $r["num_cases"]);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
echo $jsonTable;
}
?>
如您所见,json 变量仅存储查询返回的 5 列中的两列。 json变量需要存储的列是“variable”和“num_cases”。
有什么建议为什么没有使用此代码填充 json 变量?
谢谢!
【问题讨论】:
-
您可能必须执行dev.mysql.com/doc/apis-php/en/… 才能将指针重置为返回结果的开头。
-
同时检查
echo json_last_error_msg();是否打印出任何有趣的东西。将其放在json_encode语句之后。 -
@jeff 你是对的!我在 while 循环之前添加了这一行
mysqli_data_seek($results, 0);并且它起作用了。随意写它作为答案,我会接受它。