使用PHP将数据从mysql转换为JSON在本地工作,但在服务器上不起作用
我的代码在100%本地工作,并返回如下答案:使用PHP将数据从mysql转换为JSON在本地工作,但在服务器上不起作用,php,mysql,json,Php,Mysql,Json,我的代码在100%本地工作,并返回如下答案: [{"id":"1","zuzycie":"40"},{"id":"3","zuzycie":"83.333333333333"}] 服务器上的文件和代码结构相同。我没有连接到数据库的问题,所以路径很好。但是服务器上的代码正在返回[null,null,null,null,null]。有人知道怎么修吗 <?php //setting header to json header('Content-Type: application
[{"id":"1","zuzycie":"40"},{"id":"3","zuzycie":"83.333333333333"}]
服务器上的文件和代码结构相同。我没有连接到数据库的问题,所以路径很好。但是服务器上的代码正在返回[null,null,null,null,null]
。有人知道怎么修吗
<?php
//setting header to json
header('Content-Type: application/json');
require_once "../polaczenie.php";
//get connection
$mysqli = @new mysqli($host,$db_user,$db_password,$db_name);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT id, zuzycie FROM zuzycie_paliwa ORDER BY id ");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//free memory associated with result
$result->close();
//close connection
$mysqli->close();
//now print the data
print json_encode($data);
?>
我怀疑它是否能在本地工作,因为您正在尝试遍历mysqli结果。尝试将foreach循环替换为
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
您的服务器数据库中有数据吗
var_dump
您的$data
变量。是的,在5.4中添加了id=1和zuzycie=100迭代器支持。它可能在OP的本地环境中工作,因为他们的PHP版本比那个版本更新,反之亦然。