0

I have a basic MySQL database table People with 3 columns (ID, Name, Distance)

I am trying to output this with PHP as a JSON so my web app can pick it up. I tried using the solution from another answer:

$sth = mysql_query($con,"SELECT * FROM People");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

However I am just returning a blank array of [].

Update: Changed to mysqli and added dumps:

$sth = mysqli_query("SELECT * FROM Events",$con);
$rows = array();
var_dump($sth);
while($r = mysqli_fetch_assoc($sth)) {
var_dump($rows); 
$rows[] = $r;
}
print json_encode($rows);

Returns:

NULL []

3

4 Answers 4

4

Swap your query and connection in the mysql_query-statement:

$sth = mysql_query("SELECT * FROM People", $con);

Besides that, the mysql-library is deprecated. If you're writing new code consider using mysqli_ or PDO.

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

2 Comments

Depends, if you have more than one connection (I guess he doesn't) you should provide it
Nope, mysql_query will just use the last connection. Anyway, the OP should stop using the mysql_* functions.
0

Why no mysql_connect ?

var_dump($sth);   // check the return of mysql_query()
var_dump($rows);  // check the array of mysql_fetch_assoc result 

Comments

0

I would check if your query is returning any rows first.

<?php
$rows = array();

array_push($rows, array("name" => "John"));
array_push($rows, array("name" => "Jack"));
array_push($rows, array("name" => "Peter"));

print  json_encode($rows);
?>

Produces this output.

[{"name":"John"},{"name":"Jack"},{"name":"Peter"}]

Comments

0

Solved using a combination of answer to get:

$sth = mysqli_query($con,"SELECT * FROM Events");
$datarray = array();
while($row = mysqli_fetch_assoc($sth)) {
$datarray[] = $row;
}
print_r(json_encode($datarray));

Comments

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.