PHP foreach循环返回null vaule

时间:2018-06-11 07:06:32

标签: php mysql json

我想将我的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数据 this is my sql data

如何修复它。 我搜索我尝试但不工作。

2 个答案:

答案 0 :(得分:2)

MySQLi要求您先获取数据,不能循环查询对象。摆脱你的foreach循环并使用

while ($row = $result->fetch_assoc()) { 
    data[] =  $row;
}

答案 1 :(得分:0)

试试这个逻辑

while ($row = $result->fetch_row()) {
$data[] = $row;
}