JSON encode MySQL results
How do I use the json_encode()
function with MySQL query results? Do I need to iterate through the rows or can I just apply it to the entire results object?
Solution 1:
$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
The function json_encode
needs PHP >= 5.2 and the php-json package - as mentioned here
NOTE: mysql
is deprecated as of PHP 5.5.0, use mysqli
extension instead http://php.net/manual/en/migration55.deprecated.php.
Solution 2:
Try this, this will create your object properly
$result = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['object_name'][] = $r;
}
print json_encode($rows);
Solution 3:
http://www.php.net/mysql_query says "mysql_query()
returns a resource".
http://www.php.net/json_encode says it can encode any value "except a resource".
You need to iterate through and collect the database results in an array, then json_encode
the array.
Solution 4:
Thanks.. my answer goes:
if ($result->num_rows > 0) {
# code...
$arr = [];
$inc = 0;
while ($row = $result->fetch_assoc()) {
# code...
$jsonArrayObject = (array('lat' => $row["lat"], 'lon' => $row["lon"], 'addr' => $row["address"]));
$arr[$inc] = $jsonArrayObject;
$inc++;
}
$json_array = json_encode($arr);
echo $json_array;
}
else{
echo "0 results";
}
Solution 5:
The code below works fine here!
<?php
$con=mysqli_connect("localhost",$username,$password,databaseName);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "the query here";
$result = mysqli_query($con,$query);
$rows = array();
while($r = mysqli_fetch_array($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>