Liz Banach Liz Banach - 4 months ago 8
PHP Question

Convert mySQL database query to JSON in PHP

I am using the following code to connect to my local database and query results from a table. The following code is not working to print my results in a JSON format. Is there something I am missing? Thanks for your help!

<?php

if (!$link = mysql_connect('localhost', 'root', 'root')) {
echo 'Could not connect to mysql';
exit;
}

if (!mysql_select_db('tm-charts', $link)) {
echo 'Could not select database';
exit;
}

$sql = 'SELECT Name,status FROM Estimates';
$result = mysql_query($sql, $link);

if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}

$rows = array();

while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}

echo json_encode($rows);

?>

Answer

Correction: Your comment indicates you are getting the encoded array, but you don't receive it as JSON, to solve this you have to set the header first:

header('Content-Type: application/json; charset=utf-8');

It's important that you make no output before calling the header function. An empty line not inside php tags is already an output (also in the includes).


Second possibility: some of the cells contain illegal characters and then json_encode fails.

Comments