0

I want to fetch my sql data to json It work when I try in xampp

but when I load to server It return null value

$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);

And this is result when I run

Initial character set: latin1
Current character set: utf8
[null,null,null,null,null]

this is my sql data this is my sql data

How to fix it. I search I try but not work.

TooKom
  • 35
  • 6
  • Make sure database name and credentials are right. Also database exists with same name on server. – Lovepreet Singh Jun 11 '18 at 07:07
  • `var_dump($data)`, `var_dump(json_last_error_msg())`? – deceze Jun 11 '18 at 07:21
  • 1
    MySQLi requires you to fetch the data first, you can't loop the query object. Get rid of your foreach loop and use `while ($row = $result->fetch_assoc()) {` instead – Qirel Jun 11 '18 at 07:28

2 Answers2

2

MySQLi requires you to fetch the data first, you can't loop the query object. Get rid of your foreach loop and use

while ($row = $result->fetch_assoc()) { 
    data[] =  $row;
}
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • While this is a more traditional working syntax, I fully disagree that the result set object is not traversable. https://stackoverflow.com/questions/41199041/mysqli-result-foreach-resultset-converted-to-array I reckon something else was wrong in the OP's project. – mickmackusa Sep 28 '19 at 09:40
  • Or do you know this to be a xampp issue? – mickmackusa Sep 28 '19 at 09:47
0

Try this logic

while ($row = $result->fetch_row()) {
$data[] = $row;
}
SynapseIndia
  • 450
  • 2
  • 10