Lichen5221 / Report-Daily

記錄每日上課內容與作業。
0 stars 0 forks source link

2021-07-24 #60

Open Lichen5221 opened 3 years ago

Lichen5221 commented 3 years ago

老師寫的留言板 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 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'],
      "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;
?>