Database records converted to JSON format (2011-03-13-19:48:37)

Source: Internet
Author: User

Http://blog.sina.com.cn/s/blog_621768f30100r6v7.html

Convert database records into JSON format(2011-03-13 19:48:37) reproduced
Tags: gossip
<?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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.