php簡(jiǎn)單實(shí)現(xiàn)查詢數(shù)據(jù)庫返回json數(shù)據(jù)

字號(hào):


    示例代碼一:
    // 設(shè)置返回json格式數(shù)據(jù)
    header('content-type:application/json;charset=utf8');
    //連接數(shù)據(jù)庫
    $link = mysql_connect("localhost", "root", "root") or die("Unable to connect to the MySQL!");
    mysql_query("SET NAMES 'UTF8'");
    mysql_select_db("jilinwula", $link) or die("Unable to connect to the MySQL!");
    // 獲取分頁參數(shù)
    $page = 0 ;
    $pageSize = 3;
    if(!is_null($_GET["page"])) {
    $page = $_GET["page"];
    }
    if(!is_null($_GET["pageSize"])) {
    $pageSize = $_GET["pageSize"];
    }
    // 查詢數(shù)據(jù)到數(shù)組中
    $result = mysql_query("select username,password from userinfo limit " . $page . ", ". $pageSize ."");
    $results = array();
    while ($row = mysql_fetch_assoc($result)) {
    $results[] = $row;
    }
    // 將數(shù)組轉(zhuǎn)成json格式
    echo json_encode($results);
    // 關(guān)閉連接
    mysql_free_result($result);
    mysql_close($link);
    示例代碼二:
    <?php
    //需要執(zhí)行的SQL語句
    //單條
    $sql="select id,name from tbl_user where id=1";
    //多條數(shù)據(jù)
    //$sql="select id,name from tbl_user";
    //調(diào)用conn.php文件進(jìn)行數(shù)據(jù)庫操作
    require('Conn.php');
    //提示操作成功信息,注意:$result存在于conn.php文件中,被調(diào)用出來
    if($result)
    {
    // $array=mysql_fetch_array($result,MYSQL_ASSOC);
    /*數(shù)據(jù)集
    $users=array();
    $i=0;
    while($row=mysql_fetch_array($result,MYSQL_ASSOC)){
    echo $row['id'].'-----------'.$row['name'].'</br>';
    $users[$i]=$row;
    $i++;
    }
    echo json_encode(array('dataList'=>$users));
    */
    /*單條數(shù)據(jù)*/
    $row=mysql_fetch_row($result,MYSQL_ASSOC);
    echo json_encode(array('jsonObj'=>$row));
    }
    mysql_free_result($result);
    //釋放結(jié)果
    mysql_close();
    //關(guān)閉連接
    ?>