我正在使用最新的 xamp 在本地主机上运行我的页面,它从表中获取数据并创建 json 字符串。用于谷歌图表创建。在本地主机上,它工作得很好。
相同的代码,我放在 linux ec2 实例上的数据库。它采用错误的 json 字符串并且不给出结果。
是因为 xamp 版本差异吗?
本地主机有PHP 5.4.16
和ec2服务器PHP 5.3.8
。
代码是:
<?php
$mysqli =mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = $mysqli->query('SELECT * FROM view_name');
$rows = array();
$table = array();
$table['cols'] = array(
array('label' => 'pcount', 'type' => 'string'),
array('label' => 'ncount', 'type' => 'number')
);
/* Extract the information from $result */
foreach($result as $r) {
$temp = array();
$temp[] = array('v' => (string) $r['ind_type']);
$temp[] = array('v' => (int) $r['Index_val']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
// convert data into JSON format
//$jsonTable = json_encode($table);
$jsonTable = json_encode($table);
echo $jsonTable;
?>
在本地主机上,它给出 JSON 字符串
{"cols":[{"label":"pcount","type":"string"},{"label":"ncount","type":"number"}],"rows":[{"c":[{"v":"pcount"},{"v":179}]},{"c":[{"v":"ncount"},{"v":237}]}]}
我在 ec2 实例上运行时的 json 字符串:
{"cols":[{"label":"pcount","type":"string"},{"label":"ncount","type":"number"}],"rows":[{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]},{"c":[{"v":""},{"v":0}]}]}
表是:
+----------+-----------+
| ind_type | Index_val |
+----------+-----------+
| pcount | 179 |
| ncount | 237 | which is same on localhost and ec2 instance.
+----------+-----------+
我可能是错的,因为我使用 pdo 而不是 mysqli,但你不应该做一个$result->fetch_assoc()
来获取一个关联数组,如下所述:http://php.net/manual/en/mysqli-result.fetch-assoc.php?
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)'n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
顺便说一下,我认为您混合了面向对象的样式和过程样式。请参阅 php.net 上的示例 1 和示例 2。