0

Possible Duplicate:
JSON encode MySQL results

This is using the Mysql fetch array to display the result. how can i replace the following tags using JSON encode. I am trying to get a table from a database, and this does the job of outputting a data... this is using the Mysql fetch array to display the result. how can i replace the following tags using JSON encode.

PHP File 
<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>
Community
  • 1
  • 1
floormind
  • 1,868
  • 5
  • 31
  • 85
  • 3
    I have absolutely no idea what you are asking, but [Bobby Tables](http://bobby-tables.com/) would love to come and play. – Quentin Dec 20 '11 at 18:14
  • Do you want sql result returned with ajax in the json format? – JercSi Dec 20 '11 at 18:59
  • 1
    The sample code is vulnerable to [SQL injection](http://unixwiz.net/techtips/sql-injection.html), which is a very serious [security risk](http://bobby-tables.com/). To fix this hole, switch from the outdated mysql extension to [PDO](http://php.net/PDO) and use [prepared statements](http://www.php.net/PDO.prepared-statements), passing values as parameters to the statement rather than interpolating them directly into the string. If you need a PDO tutorial, try ["Writing MySQL Scripts with PHP and PDO"](http://www.kitebird.com/articles/php-pdo.html). The site you save may just be your own. – outis Dec 20 '11 at 19:18
  • Yeah, illd like the sql result returned with ajax in json format .. – floormind Dec 20 '11 at 21:30
  • There is a matching question + answer concerning the string-type-problem at: http://stackoverflow.com/questions/28261613/convert-mysql-result-to-json-with-correct-types – Marcel Ennix Feb 01 '15 at 11:27

1 Answers1

0
<?php
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
print json_encode($rows);
Kenaniah
  • 5,171
  • 24
  • 27