這篇文章主要介紹了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();//關閉串連?>
總結:以上就是本篇文的全部內容,希望能對大家的學習有所協助。
相關推薦:
php實現網頁緩衝的工具類的代碼及使用方法
php基於ajax實現控制所有後台函數調用
php檔案上傳所涉及的檔案與表單操作及資料庫操作