这个问题在这里已经有答案了:
如何将mysqli结果转换为json(6个答案)
去年关门了。
我想把我的sql数据提取到json中,当我尝试xampp时,它就可以工作了
但当我加载到服务器时,它返回空值
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("Initial character set: %s\n", $mysqli->character_set_name());
/* change character set to utf8 */
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
//query to get data from the table
$query = sprintf("SELECT playerid, score FROM score ORDER BY playerid");
//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);
这就是我跑步的结果
Initial character set: latin1
Current character set: utf8
[null,null,null,null,null]
这是我的sql数据
如何修复。我搜索我尝试但不工作。
2条答案
按热度按时间bsxbgnwa1#
mysqli要求首先获取数据,不能循环查询对象。摆脱foreach循环并使用
http://php.net/manual/en/mysqli-result.fetch-assoc.php
0tdrvxhp2#
试试这个逻辑