-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.

4

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

3 Comments

Why will this fix the problem? Seems the OP has no problem fetching rows.
@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".
But the issue here looks to be the json encoding. Not necessarily their database connection.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.