api allow specify id

This commit is contained in:
Zichao Lin 2023-11-25 20:31:08 +08:00
parent 839f79eca2
commit ba26402705
Signed by: earthjasonlin
GPG Key ID: 406D9913DE2E42FB

26
api.php

@ -3,11 +3,21 @@
header('Content-type: application/json'); header('Content-type: application/json');
//载入数据库文件 //载入数据库文件
require("data.php"); require("data.php");
//检查是否有指定id
if (isset($_GET['id'])) {
$id = $_GET['id'];
//查询指定id的记录
$sql = "SELECT * FROM soul WHERE id = $id";
} else {
//查询随机一条记录 //查询随机一条记录
$sql = "SELECT * FROM soul ORDER BY RAND() LIMIT 1"; $sql = "SELECT * FROM soul ORDER BY RAND() LIMIT 1";
}
$result = mysqli_query($conn, $sql); $result = mysqli_query($conn, $sql);
//检查是否查询成功
if ($result) {
$row = mysqli_fetch_assoc($result); $row = mysqli_fetch_assoc($result);
//输出json //检查是否找到记录
if (mysqli_num_rows($result) > 0) {
echo json_encode(array( echo json_encode(array(
"code" => 0, "code" => 0,
"message" => "OK", "message" => "OK",
@ -18,3 +28,17 @@ echo json_encode(array(
"from" => $row["from"] "from" => $row["from"]
) )
)); ));
} else {
echo json_encode(array(
"code" => 1,
"message" => "No results found",
"data" => null
));
}
} else {
echo json_encode(array(
"code" => 2,
"message" => "Error executing query",
"data" => null
));
}