Liz Banach Liz Banach - 1 year ago 98
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!


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

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

$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();

$rows = array();

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

echo json_encode($rows);


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download