-3

I'm running PHP and MySQL and have the following code:

$data = array();
$result = mysql_query($search_query);
if ($result){
    while($row = mysql_fetch_assoc($result)) {
        $data[] = $row;
    }
    if (sizeof($data) > 0) {
        //var_dump($data);
        echo json_encode($data);
    } else {
      echo 'empty';
    }
}

If my query has no rows I do get empty returned. But if there's any records I get a Resource has no content in Safari.

But if I uncomment my //var_dump($data); then I do get a nice array of values.

Can O' Spam
  • 2,718
  • 4
  • 19
  • 45
Alfred Balle
  • 1,135
  • 4
  • 16
  • 32
  • Possible duplicate of [php JSON\_encode not working](https://stackoverflow.com/questions/41972084/php-json-encode-not-working) – JustBaron Jun 25 '18 at 10:45
  • 1
    Take a look at your out of date `mysql_` functions: https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php?rq=1 – JustBaron Jun 25 '18 at 10:47
  • What does `json_last_error()` say? http://php.net/manual/en/function.json-last-error-msg.php – Mr Glass Jun 25 '18 at 10:48
  • ` $res = array_map('utf8_encode', $res); ` sovled it. Thank you. – Alfred Balle Jun 25 '18 at 10:52

1 Answers1

0

Try this:

// Database connection.
$mysqli = new mysqli('localhost', 'user', 'password', 'db_name');

// Your query.
$search_query = "SELECT * FROM yuor_table";

$data = array();
$result = $mysqli->query($search_query);
if ($result){
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
    if (sizeof($data) > 0) {
        //var_dump($data);
        echo json_encode($data);
    } else {
      echo 'empty';
    }
}

This is very simple solution. I would suggest to use "mysqli".

Vincenzo
  • 19
  • 3
  • Why will this fix the problem? Seems the OP has no problem fetching rows. – Progrock Jun 25 '18 at 11:20
  • @Progrock I suppose that the real problem is not procedural style but wrong use of "mysql" function during connection or database selection. Anyway, "mysqli" extension is much more indicated than deprecated "mysql". – Vincenzo Jun 25 '18 at 12:48
  • But the issue here looks to be the json encoding. Not necessarily their database connection. – Progrock Jun 25 '18 at 12:50