首先,在数据库中创建一个名为 notes 的表,包含以下字段:
id:笔记 ID,自增长整数类型
room_id:自习室 ID,整数类型
user_id:用户 ID,整数类型
content:笔记内容,字符串类型
created_at:创建时间,时间戳类型
创建一个名为 addNote 的 API,用于向数据库中添加笔记。
php
Copy code
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 获取请求参数
$room_id = $_POST['room_id'];
$user_id = $_POST['user_id'];
$content = $_POST['content'];
$created_at = time();
// 插入数据到数据库
$sql = "INSERT INTO notes (room_id, user_id, content, created_at)
VALUES ('$room_id', '$user_id', '$content', '$created_at')";
mysqli_query($conn, $sql);
// 返回结果
$response = array(
'code' => 0,
'msg' => 'success',
);
echo json_encode($response);
创建一个名为 getNotes 的 API,用于获取某个自习室的所有笔记。
/
/ 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 获取请求参数
$room_id = $_GET['room_id'];
// 从数据库中获取笔记
$sql = "SELECT * FROM notes WHERE room_id = '$room_id'";
$result = mysqli_query($conn, $sql);
// 将结果转换成数组
$notes = array();
while ($row = mysqli_fetch_assoc($result)) {
$notes[] = $row;
}
// 返回结果
$response = array(
'code' => 0,
'msg' => 'success',
'data' => $notes,
);
echo json_encode($response);
创建一个名为 shareNote 的 API,用于将某个笔记分享给其他自习室成员。
// 连接数据库
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// 获取请求参数
$note_id = $_POST['note_id'];
$room_id = $_POST['room_id'];
$user_id = $_POST['user_id'];
// 查询笔记是否存在
$sql = "SELECT * FROM notes WHERE id = '$note_id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if (!$row) {
$response = array(
'code' => -1,
'msg' => 'note not found',
);
echo json_encode($response);
exit;
}
// 查询用户是否在自习室中
$sql = "SELECT * FROM room_users WHERE room_id = '$room_id' AND user_id = '$user_id'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
if (!$row) {
$response = array(
"status" =>