1

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

?>
Liz
  • 1,008
  • 5
  • 19
  • 49
  • http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – AbraCadaver Aug 01 '16 at 20:24
  • 4
    mysql_ functions are deprecated and shouldn't be used any more. With that said, I can't immediately see an issue with the code. Do you get any output at all? What does `var_dump($rows);` give? – rjdown Aug 01 '16 at 20:25
  • Run this script from your browser. Do you see the JSON String on the page output? – RiggsFolly Aug 01 '16 at 20:32
  • @rjdown Thank you for your reply! var_dump($rows); returns an array of the Name and status from the query. Why is this not converting into JSON when I use echo json_encode($rows); ? Also, before I added in the var_dump(); my page was the white screen of death. – Liz Aug 01 '16 at 20:32
  • @riggsfolly Which script should I run? – Liz Aug 01 '16 at 20:37
  • The one you just showed us. If it works it should show you the JSON String – RiggsFolly Aug 01 '16 at 20:39

1 Answers1

0

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.
maraca
  • 8,468
  • 3
  • 23
  • 45
  • Including that code, as well as using: mysql_set_charset("UTF8", $link); worked! – Liz Aug 01 '16 at 21:00