這篇文章主要介紹了php簡單實現查詢數據庫返回json數據,并附上2則示例代碼,非常的簡單實用,有需要的小伙伴可以參考下。
示例代碼一:
- // 設置返回json格式數據
- header('content-type:application/json;charset=utf8');
- //連接數據庫
- $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!");
- // 獲取分頁參數
- $page = 0 ;
- $pageSize = 3;
- if(!is_null($_GET["page"])) {
- $page = $_GET["page"];
- }
- if(!is_null($_GET["pageSize"])) {
- $pageSize = $_GET["pageSize"];
- }
- // 查詢數據到數組中
- $result = mysql_query("select username,password from userinfo limit " . $page . ", ". $pageSize ."");
- $results = array();
- while ($row = mysql_fetch_assoc($result)) {
- $results[] = $row;
- }
- // 將數組轉成json格式
- echo json_encode($results);
- // 關閉連接
- mysql_free_result($result);
- mysql_close($link);
示例代碼二:
- <?php
- //需要執行的SQL語句
- //單條
- $sql="select id,name from tbl_user where id=1";
- //多條數據
- //$sql="select id,name from tbl_user";
- //調用conn.php文件進行數據庫操作
- require('Conn.php');
- //提示操作成功信息,注意:$result存在于conn.php文件中,被調用出來
- if($result)
- {
- // $array=mysql_fetch_array($result,MYSQL_ASSOC);
- /*數據集
- $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));
- */
- /*單條數據*/
- $row=mysql_fetch_row($result,MYSQL_ASSOC);
- echo json_encode(array('jsonObj'=>$row));
- }
- mysql_free_result($result);
- //釋放結果
- mysql_close();
- //關閉連接
- ?>
以上所述就是本文的全部內容了,希望大家能夠喜歡。
新聞熱點
疑難解答