用 PHP 做出 API


Posted by tzutzu858 on 2020-10-26

和之前的差異

PHP

  1. 把資料拿出來
  2. 把資料跟 HTML 結合 (UI) 在一起
  3. 回傳 HTML
    brower render 出來
    server-side render

API

  1. 把資料拿出來
  2. 變成某種格式 (JSON)
  3. 回傳
    JS => render
    HTML => 空的
<?php
$comments = array();
array_push($comments, array(
  "id"=>1,
  "username" =>"aaa",
  "content" => "123"
)); 
// array_push(array,value1,value2...) 第一個參數規定要一個數組和第二個參數要添加的值是必須

array_push($comments, array(
  "id"=>2,
  "username" =>"bbb",
  "content" => "456"
));

$json = array("comments" =>$comments);
$response = json_encode($json);//json_encode : 返回字符串,包含了 value 值 JSON 形式的表示。
header('Content-type:application/json;charset=utf-8');
echo $response;
?>

印出 $comments 長這樣

Array ( [0] => Array ( [id] => 1 [username] => aaa [content] => 123 ) [1] => Array ( [id] => 2 [username] => bbb [content] => 456 ) )

印出 $json

Array ( [comments] => Array ( [0] => Array ( [id] => 1 [username] => aaa [content] => 123 ) [1] => Array ( [id] => 2 [username] => bbb [content] => 456 ) ) )

echo $response 的結果是

{"comments":[{"id":1,"username":"aaa","content":"123"},{"id":2,"username":"bbb","content":"456"}]}

所以 $response 就是一個 json 物件,裡面有 comments 這個 key ,這個 key 底下存的是一個陣列
可以打開 DevTools 來看

實作列出所有文章的 api

<?php
  require_once("conn.php");

  $page = 1;
  if (!empty($_GET['page'])) {
    $page = intval($_GET['page']);
  }
  $items_per_page = 10;
  $offset = ($page - 1) * $items_per_page;

  $stmt = $conn->prepare(
    'SELECT ' .
    'C.id AS id, C.content AS content, ' .
    'C.created_at AS created_at, U.nickname AS nickname, U.username AS username ' .
    'FROM tzu_comments AS C ' .
    'LEFT JOIN tzu_users AS U on C.username = U.username ' .
    'WHERE C.is_deleted IS NULL ' .
    'ORDER BY C.id DESC ' .
    'LIMIT ? OFFSET ?'
  );
  $stmt->bind_param('ii', $items_per_page, $offset);
  $result = $stmt->execute();
  if (!$result) {
    die('Error:' . $conn->error);
  }
  $result = $stmt->get_result();
  $comments = array();

  while($row = $result->fetch_assoc()) {
    array_push($comments, array(
      "id"=> $row['id'],
      "username" => $row['username'],
      "nickname" => $row['nickname'],
      "content" => $row['content'],
      "created_at" => $row['created_at']
    ));
  }

  $json = array(
    "comments" => $comments
  );

  $response = json_encode($json);
  header('Content-type:application/json;charset=utf-8');
  echo $response;
?>

這樣就完成了 http://tzutzu858.tw/week11_hw1/api_comments.php
也可以用帶參數的方式 http://tzutzu858.tw/week11_hw1/api_comments.php?page=2










Related Posts

MTR04_0712

MTR04_0712

Week1: CLI 和 Git 筆記

Week1: CLI 和 Git 筆記

Angular 9 + Firebase (1) : AngularFire 快速安裝

Angular 9 + Firebase (1) : AngularFire 快速安裝


Comments