-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.php
105 lines (88 loc) · 2.45 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
require('helpers.php');
function api ($path, $db) {
$response = null;
$method = $_SERVER['REQUEST_METHOD'];
if (preg_match('/^\/todos$/', $path)) {
switch ($method) {
case 'GET':
$query = "SELECT * FROM todos;";
$result = $db->query($query);
$all_data = $result->fetch_all();
$response = [];
foreach ($all_data as $key => $values) {
$keys = [
'id',
'description',
'completed',
'createdAt'
];
$combined = array_combine($keys, $values);
$combined['completed'] = (boolean) $combined['completed'];
array_push($response, $combined);
}
header('Content-Type: application/json');
break;
case 'POST':
$json = file_get_contents('php://input');
$decoded = json_decode($json);
$description = $decoded->description;
$completed = $decoded->completed;
$created_at = $decoded->createdAt;
$query = "INSERT INTO todos (
description,
completed,
created_at
) VALUES (
'$description',
'$completed',
'$created_at'
);
";
$db->query($query);
if ($db->errno)
http_response_code(500);
else
http_response_code(201);
break;
default:
echo 'Method not allowed';
break;
}
} else if (preg_match('/^\/todos\/\d+$/', $path)) {
$todo_id = explode('/', $path)[2];
switch ($method) {
case 'DELETE':
$query = "DELETE FROM todos WHERE id = '$todo_id';";
$db->query($query);
if ($db->errno)
http_response_code(500);
else
http_response_code(200);
break;
case 'PUT':
$json = file_get_contents('php://input');
$decoded = json_decode($json);
$description = $decoded->description;
$completed = (int) $decoded->completed;
$query = "UPDATE todos
SET description = '$description',
completed = '$completed'
WHERE id = '$todo_id';
";
$db->query($query);
if ($db->errno)
http_response_code(500);
else
http_response_code(200);
break;
default:
echo 'Method not allowed';
break;
}
} else {
header('HTTP/1.0 404 Not Found');
}
if ($response)
echo json_encode($response);
}