0

My code looks like this:

$hostname = 'myhost.com';
$database = 'heading';
$username = 'me';
$password = 'pw';
$dbh = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * from mytable";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//var_dump($result); //This works and dumps the array with the right data
header('Content-type: application/json');
echo json_encode($result);

This echos nothing back though. No errors, just nothing. If I try echo($result) this echos "Array".

What's happening here?

jonmrich
  • 4,233
  • 5
  • 42
  • 94
  • echo is no good for outputting arrays. Use var_dump or print_r. – CBroe Mar 02 '16 at 21:20
  • 2
    @CBroe echo should work as he is echoing a json string. – CodeGodie Mar 02 '16 at 21:21
  • I can `print_r` my variable `$result`, but it's an array versus a JSON object. – jonmrich Mar 02 '16 at 21:22
  • @MarcB I know that. I think your message is suppose to be for CBroe – CodeGodie Mar 02 '16 at 21:24
  • What happens if you remove header? – Muhammed Mar 02 '16 at 21:24
  • 1
    make sure that json itself didn't fail. e.g. `var_dump(json_encode(...));` would show a boolean false if the encoding failed, and then you'd check `json_last_error()` for the reason why. print_r won't show boolean falses - it'll just print them as an empty zero-length string. var_dump() would show `(bool)false` – Marc B Mar 02 '16 at 21:24
  • @CodeGodie: No he’s not, he said `echo($result)` results in `Array`. – CBroe Mar 02 '16 at 21:25
  • can you provide the result set you get when you `var_dump($result)` or `print_r($result)` ? – CodeGodie Mar 02 '16 at 21:25
  • @MarcB I'm getting boolean false. `var_dump(json_last_error())` gives me int(5)...whatever that is. – jonmrich Mar 02 '16 at 21:26
  • Just to reinforce this, I tested locally and it didn't work either... – FirstOne Mar 02 '16 at 21:26
  • @FirstOne This actually worked until I did something to it, but I can't figure out what. – jonmrich Mar 02 '16 at 21:27
  • 3
    http://php.net/json_last_error error code 5 should be malformed utf-8 character. you probably haven't enabled utf8 in your php->mysql connection, and one or more utf chars in the db data got corrupted coming over to php. – Marc B Mar 02 '16 at 21:27
  • @MarcB That definitely could be it, as I just added stuff to the database. Where do I fix this? – jonmrich Mar 02 '16 at 21:28
  • http://stackoverflow.com/questions/279170/utf-8-all-the-way-through – Marc B Mar 02 '16 at 21:29
  • @MarcB I found one letter e with an accent on it in one entry. That was the problem. Thanks! – jonmrich Mar 02 '16 at 21:30

0 Answers0