0

I'm trying to fetch data from a MariaDB database of festivals and respective locations. When running:

while($row = $sth->fetch_assoc()){}

and iterating over $row while outputting the values, I get data as it is in the database. However, when storing each row like so:

while($row = $sth->fetch_assoc()){
    $results[] = $row;
}

And echoing the results as JSON (echo json_encode($results);) I get this:

{"id":"0","name":null,"village":"0","startDate":"2019-01-16",
"endDate":"2019-01-23","message":null}

This is for an existing Linux server, which I do not manage (I'm using CPanel). PHP version is 5.4 and MariaDB 10.1.37.

So far, a lot of code samples on Stack Overflow and other websites are using $results[] = $row; for storing the results. I'm returning to PHP after 3 years of Swift only programming... So I suspect this could be a simple issue to solve...

Thanks!

Renato Silva
  • 51
  • 10
  • 3
    So what's the actual issue? That row might actually have null values for those columns. Without seeing the data, it's hard to tell. – aynber Jan 14 '19 at 18:04
  • For example the "name" and "message" columns all have strings inside them... when I iterate over $row, I can echo the output. when I store each $row in $results, I can't seem to get anything other than null... which is weird because it only happens with string values. Could it be a charset issue? – Renato Silva Jan 14 '19 at 18:06
  • `var_dump($results)` what is the output, and can you provide the query you're running? – Jonnix Jan 14 '19 at 18:07
  • $sth = $mysqli->query("SELECT * FROM festivals"); – Renato Silva Jan 14 '19 at 18:09
  • var_dump works, all the data, including strings are there... what's happening? lol – Renato Silva Jan 14 '19 at 18:10
  • array(2) { [0]=> array(6) { ["id"]=> string(1) "0" ["name"]=> string(23) "Festas de Santo António" ["village"]=> string(1) "0" ["startDate"]=> string(10) "2019-01-16" ["endDate"]=> string(10) "2019-01-23" ["message"]=> string(115) "Uma vila com muito para descobrir, e tanto que fazer! Desfrute ao máximo da 28ª edição das Festas de Santo António!" } [1]=> .... } – Renato Silva Jan 14 '19 at 20:09
  • Any suggestions? Thank you – Renato Silva Jan 22 '19 at 13:07

1 Answers1

-1

May be I'm bit too late for answering this question, but it may help someone stuck with this issue. Recently I faced a similar issue and it took me 3 days to understand that it is an issue with the utf-8 characters. Data stored in database are perfectly fine. But when it comes to return it via json_encode(), it shows no data at all as json_encode only supports utf-8 data(reference).

For your case the following method should work-

foreach ($results as &$r) {
    $r['name'] = utf8_encode($r['name']);
    //same for all other items
}
Abir Partha
  • 123
  • 2
  • 8