##方案一:讀取數據庫方式開發首頁接口
流程: 從數據庫獲取信息 -> 封裝 -> 生成接口數據
應用場景:數據時效性,比較高的系統
學習要點:
1. 掌握如何獲取數據;
2. 掌握如何將獲取的數據生成通信數據;
詳細流程:
http請求 -> 服務器 -> 查詢數據 -> 返回數據
*文件鏈接:var/www/app/list.php*
```
// 封裝輸出數據類
require_once('./response.php');
// 引入的 db.php 數據庫類需要進行改動
require_once('./db.php');
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$pageSize = isset($_GET['pagesize']) ? $_GET['pagesize'] : 1;
if (!is_numeric($page) || !is_numeric($pageSize)) {
return Response::show(401, '數據不合法');
}
$offset = ($page-1) * $pageSize;
$sql = "select * from mk_user where score != 0 order by id desc limit " . $offset . "," . $pageSize;
// $sql = "select * from mk_user";
// $result = mysql_query($sql, $connect);
// echo mysql_fetch_row($result);
// var_dump($result);
try {
$connect = Db::getInstance()->connect();
} catch(Exception $e) {
return Response::show(403, '數據庫連接失敗', $users);
}
$result = mysql_query($sql, $connect);
$users = array();
while ($user = mysql_fetch_assoc($result)) {
$users[] = $user;
}
if($users) {
return Response::show(200, '首頁數據獲取成功', $users);
} else {
return Response::show(400, '首頁數據獲取失敗', $users);
}
```
*文件鏈接:var/www/app/db.php*
~~~
class Db {
static private $_instance; // 保存類的實例
static private $_connectSource; // 連接的資源
private $_dbConfig = array(
'host' => '192.168.2.110',
'user' => 'root',
'password' => 'root',
'database' => 'muke',
);
// 構造函數需要設置成私有,防止被其他類實例化
private function __construct() {
}
// 訪問實例的公共方法
static public function getInstance() {
// 是否實例,如果沒有則實例化類
if (!self::$_instance instanceof self) {
self::$_instance = new self();
}
return self::$_instance;
}
public function connect() {
if(!self::$_connectSource) {
self::$_connectSource = mysql_connect($this->_dbConfig['host'], $this->_dbConfig['user'], $this->_dbConfig['password']);
if(!self::$_connectSource) {
// 此處注意,如果數據庫連接失敗,需要拋出一個異常,以供連接時使用,連接需要用 try-catch 測試連接。
throw new Exception('mysql connect error ' . mysql_error());
// die('mysql connect error'. mysql_error());
}
mysql_select_db($this->_dbConfig['database'], self::$_connectSource);
mysql_query("set names UTF8", self::$_connectSource);
return self::$_connectSource;
}
}
}
~~~