1

This code used to work on another server I used to have which I believe was running php5.# I am not on a new server running PHP Version 7.0.15-0ubuntu0.16.04.4.

Here is my code

$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while($obj = mysqli_fetch_object($result)) {
        $var[] = $obj;
    }
}

echo json_encode($var);
echo json_encode($var[3]);

I included that second echo statement because that one works. I can get an encoding of any 1 object. However, the first echo return absolutely nothing. I have looked up this similar question all over Stackoverflow and this code seems to be the code that is in the answers. I done understand what is going wrong. Any pushing in the right direction would be greatly appreciated.

Dharman
  • 30,962
  • 25
  • 85
  • 135
James Hollyer
  • 277
  • 1
  • 3
  • 18
  • Could try `echo json_encode((array)$var);`. – ccKep Mar 20 '17 at 01:47
  • 2
    What does `json_last_error()` return ? – Darren Mar 20 '17 at 02:20
  • json_encode((array)$var); did not work. json_last_error() gave me a 5 which is JSON_ERROR_UTF8. That is a very useful function. I did some research and I tried to do a utf8_encode but that did not work. I find it strange that it has that error when encoding the array but not when encoding the individual objects in the array. Thoughts? – James Hollyer Mar 21 '17 at 04:20
  • Ok I solved it. There was one element in the array that had gotten a strange character in it. Removed that from the database and it worked. Thanks! – James Hollyer Mar 21 '17 at 04:47
  • @JamesHollyer You may want to try and future proof your code in the event that another UTF8 character pops up in you database. I've run into this before and passing the optional `JSON_UNESCAPED_UNICODE` parameter when encoding your json resolves it! - `json_encode($json, JSON_UNESCAPED_UNICODE);`. – Darren Mar 25 '17 at 23:56
  • 1
    Does this answer your question? [UTF-8 all the way through](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through) – Dharman Dec 31 '20 at 00:29
  • Checking the encoding of the database, database connection and PHP file suggested (this rather may be the actual problem - the issue which you're facing is only a symptom). Also see [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – Martin Zeitler Dec 31 '20 at 00:53

0 Answers0