-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.php
105 lines (85 loc) · 3.4 KB
/
api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
class API {
private $conn;
public function __construct() {
$host = 'localhost';
$user = 'ar1382_main';
$password = '^fGrpYzM#+Y(';
$database = 'ar1382_api';
$this->conn = new mysqli($host, $user, $password, $database);
if($this->conn->connect_error){
http_response_code(500);
die();
}
}
public function handleRequest() {
$method = $_SERVER['REQUEST_METHOD'];
switch($method) {
case 'GET':
$this->handleGet();
break;
case 'POST':
$this->handlePost();
break;
default:
http_response_code(405);
break;
}
}
public function handleGet() {
$oid = isset($_GET['oid']) ? $_GET['oid'] : null;
if($oid == null) {
http_response_code(400);
} else {
$sql = "SELECT id, DATE_FORMAT(date, '%d %M %Y') AS date, name, comment FROM apiTable WHERE oid = ? ORDER BY date ASC";
$stmt = $this->conn->prepare($sql);
$stmt->bind_param('s', $oid);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows > 0) {
http_response_code(200);
$response = array();
while($row = $result->fetch_assoc()) {
$response[] = $row;
}
$finalResponse = array('oid' => $oid, 'comments' => $response);
header('Content-Type: application/json');
echo json_encode($finalResponse);
} else {
http_response_code(204);
}
}
}
public function handlePost() {
$oid = isset($_POST['oid']) && trim($_POST['oid']) !== '' ? $_POST['oid'] : null;
$name = isset($_POST['name']) && trim($_POST['name']) !== '' ? $_POST['name'] : null;
$comment = isset($_POST['comment']) && trim($_POST['comment']) !== '' ? $_POST['comment'] : null;
if($oid == null || $name == null || $comment == null) {
http_response_code(400);
} else {
if (strlen($name) > 64 || strlen($oid) > 32) {
http_response_code(400);
} else {
$sql = "INSERT INTO apiTable (oid, name, comment) VALUES (?,?,?)";
$stmt = $this->conn->prepare($sql);
$stmt->bind_param('sss', $oid, $name, $comment);
$stmt->execute();
if($stmt->affected_rows > 0) {
http_response_code(201);
$id = $this->conn->insert_id;
$response = array('id' => $id);
header('Content-Type: application/json');
echo json_encode($response);
} else {
http_response_code(500);
}
}
}
}
public function __destruct() {
$this->conn->close();
}
}
$api = new API();
$api->handleRequest();
?>