[XAMPP][PHP] 讀取資料庫顯示,現在要來製作Restful API,因為我想讓行動裝置呼叫。
Restful API 回傳 JSON如下,透過Chrome外掛,讓JSON格式顯示得相當漂亮!
![[XAMPP][PHP] 製作Restful API2](https://cg2010studio.com/wp-content/uploads/2016/08/xamppphp-e8a3bde4bd9crestful-api2.png?w=540)
在phpMyAdmin中設定資料如下:
![[XAMPP][PHP] 製作Restful API](https://cg2010studio.com/wp-content/uploads/2016/08/xamppphp-e8a3bde4bd9crestful-api.png?w=540)
程式碼的部分研究如下:
<?php
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
// connect to the mysql database
$link = mysqli_connect('localhost', 'test', '123456', 'HappyTest');
mysqli_set_charset($link,'utf8');
// retrieve the table and key from the path
$table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
$key = array_shift($request)+0;
// create SQL based on HTTP method
switch ($method) {
case 'GET':
$sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
case 'PUT':
$sql = "update `$table` set $set where id=$key"; break;
case 'POST':
$sql = "insert into `$table` set $set"; break;
case 'DELETE':
$sql = "delete `$table` where id=$key"; break;
}
// excecute SQL statement
$result = mysqli_query($link,$sql);
// die if SQL statement failed
if (!$result) {
http_response_code(404);
die(mysqli_error());
}
// print results, insert id or affected row count
if ($method == 'GET') {
if (!$key) echo '[';
for ($i=0;$i<mysqli_num_rows($result);$i++) { echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
}
if (!$key) echo ']';
} elseif ($method == 'POST') {
echo mysqli_insert_id($link);
} else {
echo mysqli_affected_rows($link);
}
// close mysql connection
mysqli_close($link);
日後要製作什麼樣的API,存取資料庫不再是問題囉~
隨意留個言吧:)~