-
Notifications
You must be signed in to change notification settings - Fork 2
/
php_api_demo.php
123 lines (81 loc) · 2.59 KB
/
php_api_demo.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
<?php
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'POST': // create data
$data = json_decode(file_get_contents('php://input'), true); // true means you can convert data to array
// print_r($data);
postOperation($data);
break;
case 'GET': // read data
getOperation();
break;
case 'PUT': // update data
$data = json_decode(file_get_contents('php://input'), true); // true means you can convert data to array
putOperation($data);
break;
case 'DELETE': // delete data
$data = json_decode(file_get_contents('php://input'), true); // true means you can convert data to array
deleteOperation($data);
break;
default:
print('{"result": "Requested http method not supported here."}');
}
// functions
function putOperation($data){
include "db.php";
$id = $data["id"];
$name = $data["name"];
$phone = $data["phone"];
$area = $data["address"]["area"];
$road = $data["address"]["road"];
$fullAddress = $area . ", " . $road;
$sql = "UPDATE demo_api SET name = '$name', phone = '$phone', address = '$fullAddress', exe_time = NOW() WHERE id = '$id'";
if (mysqli_query($conn, $sql) or die()) {
echo '{"result": "Success"}';
} else {
echo '{"result": "Sql error"}';
}
}
function getOperation(){
include "db.php";
$sql = "SELECT * FROM demo_api";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows["result"][] = $r; // with result object
// $rows[] = $r; // only array
}
echo json_encode($rows);
} else {
echo '{"result": "No data found"}';
}
}
function postOperation($data){
// print_r($data);
include "db.php";
$name = $data["name"];
$phone = $data["phone"];
$area = $data["address"]["area"];
$road = $data["address"]["road"];
$fullAddress = $area . ", " . $road;
$sql = "INSERT INTO demo_api(name, phone, address, exe_time) VALUES('$name', '$phone', '$fullAddress', NOW())";
if (mysqli_query($conn, $sql)) {
echo '{"result": "Success"}';
} else {
echo '{"result": "Sql error"}';
}
}
function deleteOperation($data){
include "db.php";
$id = $data["id"];
$sql = "DELETE FROM demo_api WHERE id = $id";
if (mysqli_query($conn, $sql)) {
echo '{"result": "Success"}';
} else {
echo '{"result": "Sql error"}';
}
}
?>