接口寫法流程
<?php
header("Content-type: text/html; charset=utf-8");
// 包含數(shù)據(jù)庫配置信息
include_once('../config.php');
// 接收數(shù)據(jù)
// $id = isset($_REQUEST['id'])?$_REQUEST['id']:'';
// 用于返回數(shù)據(jù)
$return = array();
$data = array();
/* mysqli 面向?qū)ο?編程方式 */
// 1 . 創(chuàng)建數(shù)據(jù)庫鏈接
$conn = new mysqli($servername,$username,$password,$database);
if ($conn->connect_error) {
die("連接失敗 : ".$conn->connect_error);
}
// echo "鏈接成功";
// 設(shè)置字符集(以防出錯 每次都要寫)
$conn->query("SET NAMES utf8");
// 2 . 數(shù)據(jù)操作
$sql = "SELECT * FROM mission_news order by turn;";
// 3 . 執(zhí)行一條語句
$ret = $conn->query($sql);
// 顯示查詢 結(jié)果 結(jié)構(gòu)
// var_dump($ret); // 為什么為空
// echo $ret->num_rows; // 有值
// 4 . 循環(huán)獲取每條記錄
if ($ret->num_rows > 0) {
while ($row = $ret->fetch_assoc()) { //將每條記錄以 數(shù)組形式 返回
// var_dump($row);
// echo "id = ".$row['id']." mid = ".$row['mid']." context = ".$row['context']."<br>";
$tmp = array();//臨時數(shù)組整合信息
$tmp['id'] = $row['id'];
$tmp['mid'] = $row['mid'];
$tmp['context'] = $row['context'];
$tmp['turn'] = $row['turn'];
$tmp['created'] = $row['created'];
// 臨時數(shù)組 拼接到 返回的數(shù)組中
$data[] = $tmp; // 自增
}
// 拼接返回數(shù)組
$return['result'] = 1;
$return['data'] = $data;
}
// var_dump($return);
// 5 . 關(guān)閉數(shù)據(jù)庫
$conn->close();
// 6 . 編碼為json字符串返回
echo json_encode($return);
?>
其中 config.php 文件內(nèi)包含數(shù)據(jù)庫配置信息和定義路徑常亮辩蛋;
<?php
// 定義路徑常量
define(URL,"http://www.web.com/test");
// 設(shè)置數(shù)據(jù)庫信息
$servername = "localhost";
$username = "root";
$password = "";
$database = "fudan";
?>
前端獲取數(shù)據(jù)寫法
<?php
header("Content-type: text/html; charset=utf-8");
include_once("./config.php");
// 讀取到的是json字符串
/*不可以使用相對路徑 要使用全域名執(zhí)行php文件后獲取 echo 輸出的內(nèi)容 如果使用相對路徑 則不執(zhí)行php文件 而是輸出所有字符信息 */
$data = file_get_contents(URL."/interfaces/back.php");
// json解碼為 php 對象 或 數(shù)組($data = json_decode($data,true);)
$data = json_decode($data);
var_dump($data);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
</html>