Http://blog.sina.com.cn/s/blog_621768f30100r6v7.html
Convert database records into JSON format(2011-03-13 19:48:37)
reproduced
<?php
/
1. Remove 10 data from the Company data user table and save the array
2. When converting an array to JSON format, pass it to JS
3. Use the JSON parser to convert the passed JSON string into a JSON object,
4. Print on the page with the Document.Write output statement
*/
$conn = mysql_connect ("localhost", "root", "root"); Connecting to a database
mysql_query ("Set names Utf8″); Set encoding
mysql_select_db ("Company", $conn); Select Library
$sql = "SELECT * from user limit 10″; Querying 10 data in the user table
$res = mysql_query ($sql); Execute SQL statement
$arr = Array ();
while ($row = Mysql_fetch_array ($res, MYSQL_ASSOC)) {//query out SQL
$arr [] = $row; Assigns the result of the query to the array $arr
}
$str = Json_encode ($arr); Convert an array to a JSON-formatted string
?>
<script src= "Json_parse.js" ></script> <!– introducing JSON parser –>
<table>
<tr>
<th>uid</th><th> User name </th><th> gender </th><th>email</th>
</tr>
<script>
var jsonstring = ' <?php echo $str;? > '; Pass data from PHP to JS
document.write (jsonstring);
var jsonobject = Json_parse (jsonstring); Converts a JSON string into a JSON object in JS
for (var i = 0; i < jsonobject.length; i++) {//for loop printing
document.write ("<tr>");
document.write ("<td>", Jsonobject[i].uid, "</td>");
document.write ("<td>", Jsonobject[i].username, "</td>");
document.write ("<td>", Jsonobject[i].sex, "</td>");
document.write ("<td>", Jsonobject[i].email, "</td>");
document.write ("</tr>");
}
</script>
</table>
Convert database records to JSON format (2011-03-13-19:48:37) (GO)