數(shù)據(jù)庫數(shù)據(jù)
第一步鏈接數(shù)據(jù)庫
$dbhost = 'localhost'; // MySQL服務(wù)器主機(jī)地址 $dbuser = 'root'; // mysql用戶名 $dbpass = 'root'; // mysql用戶名密碼 $dbname = 'runoob'; //數(shù)據(jù)庫名稱 $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$dbname); if(!$conn) { die('連接失敗: ' . mysqli_error($conn)); }
第二步查詢數(shù)據(jù)庫
$json = ''; $data = array(); $sql = "SELECT * FROM paging";//sql查詢語句 $result = mysqli_query($conn,$sql);
第三步獲取查詢數(shù)據(jù)
if($result){ while($row = mysqli_fetch_assoc($result)){ $user = new Class{}; //定義空對(duì)象 $user->id = $row["id"]; $user->name = urlencode($row["name"]); $user->sex = $row["sex"]; $data[]=$user; } $json = json_encode($data);//把數(shù)據(jù)轉(zhuǎn)換為JSON數(shù)據(jù). echo "{".'"user"'.":".urldecode($json)."}"; }else{ echo "查詢失敗"; }
這里要注意的是json_encode在輸出漢字的時(shí)候會(huì)被轉(zhuǎn)義,這里我們先要用urlencode轉(zhuǎn)義,然后用urldecode解析,這樣輸出的json里面漢字是完整的漢字了。