• 数据库记录转换成json格式 (2011-03-13 19:48:37) (转)


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

    数据库记录转换成json格式

     (2011-03-13 19:48:37)
    标签: 

    杂谈

     
    <?php
    /
    1.在company数据user表中取出10条数据,保存为数组
    2.在将数组转化为json格式,传递给js
    3.用json解析器将传递过来的json字符串转化为json对象,
    4.用document.write输出语句打印在页面上
    */

    $conn = mysql_connect(“localhost”,”root”,”root”);   //连接数据库
    mysql_query(“set names utf8″);                       //设置编码
    mysql_select_db(“company”,$conn);                   //选择库

    $sql = “select * from user limit 10″;               //在user表中查询10条数据
    $res = mysql_query($sql);                           //执行sql语句
    $arr = array();

    while($row = mysql_fetch_array($res,MYSQL_ASSOC)){   //查询出来sql
    $arr[] = $row;                                   //将查询出来的结果赋给数组$arr
    }

    $str = json_encode($arr);                           //将数组转化为json格式的字符串

    ?>

    <script src=”json_parse.js”></script>                   <!– 引入json解析器 –>
    <table>
    <tr>
    <th>uid</th><th>用户名</th><th>性别</th><th>email</th>
    </tr>
    <script>
    var jsonString = ‘<?php echo $str;?>’;          //传递php中的数据给js

    //document.write(jsonString);

    var jsonObject = json_parse(jsonString);           //将json字符串转化为js中的json对象

    for(var i = 0; i < jsonObject.length; i++){           //for循环打印
    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>

  • 相关阅读:
    监控mysql的存储引擎
    基于复制的高可用
    No orientation specified, and the default is
    iOS 图标、图形尺寸? iPhone、iPad、 iPod touch
    cocos2d-x3.9利用cocos引擎一键打包Android平台APK(C++小白教程)
    loaded some nib but the view outlet was not set
    IOS开发:UIAlertView使用
    UIAlertView笔记
    Xcode之外的文档浏览工具--Dash (在iOS代码库中浏览本帖)
    iOS 开发者能用上的 10 个 Xcode 插件
  • 原文地址:https://www.cnblogs.com/dlbird/p/4433006.html
Copyright © 2020-2023  润新知