API 留言板練習-Part1 : 打造後端 API


Posted by tzutzu858 on 2020-11-02

week12 作業,作一個不需要登入的留言板,目標:

  1. 留言板的 API,能夠新增留言以及顯示留言
  2. 寫一個前端頁面,串接自己寫的 API
  3. 有「載入更多」的功能

後端 API 有兩個

  • api_comments.php 顯示留言
  • api_add_comments.php 新增留言

首先要做新增評論 api_add_comments.php 的 API

1. 資料庫新增一個叫 discussions 的資料表

有五個 column

  • id
  • site_key
  • nickname
  • content
  • created_at

2. 連線

require_once("conn.php");

3. api_add_comments.php

輸出 json 要加這行 header,瀏覽器才會知道他是 json 格式的資料

header('Content-type:application/json;charset=utf-8');

要做錯誤處理,如果 content、nickname、site_key 是空,回傳一個 json 格式並 die()

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

    $response = json_encode($json); //變成 json 的格式
    echo $response;
    die();
}

錯誤處理完就可以拿資料

$site_key = $_POST['site_key'];
$nickname = $_POST['nickname'];
$content = $_POST['content'];

拿到資料可以下 sql,放資料進去查,執行

$sql = "INSERT INTO discussions(site_Key, nickname, content) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sss', $site_key, $nickname, $content); //把參數帶上去
$result = $stmt->execute();

根據他的內容來決定是否成功,做 $result 是空的錯誤處理

if (!$result) {
    $json = array(
        "ok" => false,
        "message" => $conn->error //直接把錯誤訊息給它,但一般來說不會這樣做,因為怕有敏感訊息,不過因為是練習,要知道錯誤在哪裡,所以先這樣做
    );

    $response = json_encode($json);
    echo $response;
    die();
}

如果 $result 成功,把結果用 json 格式回傳

$json = array(
    "ok" => true,
    "message" => "success",
);

$response = json_encode($json);
echo $response

4. 做好以後用 postman 測試一下


成功以後可以再去資料庫看一下


再來做拿評論 api_comments.php 的 API

1. 基本上和 api_add_comments.php 很像,拿來改一改就好

首先只要拿 $_GET['site_key'] ,用 $_GET['site_key'] 來區分不同的留言板,其它$_POST['content']) $_POST['nickname'] 可以刪一刪,用不到


2. 改 sql 子句

$sql = "SELECT nickname, content, created_at FROM discussions WHERE site_key = ? ORDER BY id DESC";

3. $result = $stmt->execute(); 執行完後因為要拿回資料,所以加上...

$result = $stmt->get_result();
$discussions = array();
while ($row = $result->fetch_assoc()) {
    array_push($discussions, array(
        "nickname" => $row["nickname"],
        "content" => $row["content"],
        "created_at" => $row["created_at"],
    ));
}

4. $result 成功,把結果用 json 格式回傳

$json = array(
    "ok" => true,
    "discussions" => $discussions,
);

$response = json_encode($json);
echo $response;

5. 做好以後用 postman 測試一下

用 GET 測試,url 帶上 site_key=tzu



api_comments.php 全部程式

<?php
require_once 'conn.php';
header('Content-type:application/json;charset=utf-8'); //要輸出 json 記得要加這行 header,瀏覽器才會知道他是 json 格式的資料
header('Access-Control-Allow-Origin: *');

if (empty($_GET['site_key'])) {
    $json = array(
        "ok" => false,
        "message" => "Please send site_key in url",
    );

    $response = json_encode($json); //變成 json 的格式
    echo $response;
    die();
}

$site_key = $_GET['site_key'];

$sql = "SELECT nickname, content, created_at FROM discussions WHERE site_key = ? ORDER BY id DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $site_key);
$result = $stmt->execute();

if (!$result) {
    $json = array(
        "ok" => false,
        "message" => $conn->error,
    );
    $response = json_encode($json);
    echo $response;
    die();
}

$result = $stmt->get_result();
$discussions = array();
while ($row = $result->fetch_assoc()) {
    array_push($discussions, array(
        "nickname" => $row["nickname"],
        "content" => $row["content"],
        "created_at" => $row["created_at"],
    ));
}

$json = array(
    "ok" => true,
    "discussions" => $discussions,
);

$response = json_encode($json);
echo $response;









Related Posts

HTML 標籤元素與屬性介紹

HTML 標籤元素與屬性介紹

[React] 一些 Hooks 的分類

[React] 一些 Hooks 的分類

NeRF: Neural Rendering 的革命性方法(—)

NeRF: Neural Rendering 的革命性方法(—)


Comments