W12_API 自己做 [ BE101 ] 實作之一


Posted by Christy on 2021-08-30

一、API 實作

實作 API_顯示所有留言

BE101_真正的實戰:留言板 - API 篇_實作無會員機制的留言板 API:列出所有文章

  1. 開一個 api_comments.php 的檔案來儲存 JSON 格式的資料

  2. 可以用一個變數把資料存起來 $comments = array();

  3. 可以用 array_push() 這個函式把資料放進去

array_push($comments, array(
  "id" => "1",
  "username"  => "aaa",
  "content" => "123"
));
  1. 可以用 print_r($comments); 把資料印出來看看

  2. 印出來的結果會長這樣:

Array ( [0] => Array ( [id] => 1 [username] => aaa [content] => 123 ) [1] => Array ( [id] => 2 [username] => bbb [content] => 456 ) )
  1. 把 JSON 格式的資料印出來
$response = json_encode($json);
header('Content-type:application/json;charest=utf-8');
echo $response;
  1. 怎麼用 PHP 輸出 JSON 格式的資料?

a. 先建立連線:require_once('conn.php');

b. 利用 stmt 拿 sql 資料

c. 把上面第三步的程式碼改寫成:

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

d. 程式碼可以參考

code_api_comments.php

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

    $page = 1;
  if (!empty($_GET['page'])) {
        $page = intval($_GET['page']);
  }

  $items_per_page = 3;
  $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 comments as C left join 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'],
            "nickname" => $row['nickname'],
            "username"  => $row['username'],
            "content" => $row['content'],
            "created_at" => $row['created_at']
        ));
    }

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

    $response = json_encode($json);
    header('Content-type:application/json;charest=utf-8');

    echo $response;
?>

e. 可以在網址上帶參數,利用 ?page=2,可以拿到第二頁的資料 (如果你的程式碼裡面有寫 $_GET['page]) 之類的就可以

遇到的困難:

  1. 跟老師寫一模一樣的程式碼,但就是無法輸出,原來是 conn.php 被我改成上傳 lidemy server 的帳號密碼了,牽一髮而動全身!幸好一下子就想到了!

實作 API_新增 comment

BE101_真正的實戰:留言板 - API 篇_實作 API:新增文章

  1. 先複製 handle_add_comment.php 的檔案,取名叫 api_add_comment.php

  2. 前面先建議連線跟給一個 header

require_once('conn.php');

header('Content-type:application/json;charest=utf-8');
  1. 處理錯誤

因為 api 需要的是回傳資料,因此把網頁導回某一頁在這裡沒用,回傳成功或失敗即可。

    if (empty($_POST['content'])
    ) {
        $json = array(
            "ok" => false,
            "message" => "Please input content"
        );

        $response = json_encode($json);
        echo $response;
        die();
    }
  1. 印出來的 api response 會長這樣
{"ok":false,"message":"Please input content"}









Related Posts

[Week 6] CSS:其他整理

[Week 6] CSS:其他整理

關於 Shell Script

關於 Shell Script

DAY40:Are they the "same"?

DAY40:Are they the "same"?


Comments