-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.php
80 lines (61 loc) · 1.91 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
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('localhost', 'root', 'abir', 'vuephp');
$conn->connect_error ? die('Could not connect to database') : '';
$res = array('error' => false);
$action = isset($_GET['action']) ? $_GET['action'] : 'read';
if($action == 'read'){
$result = $conn->query("SELECT * FROM `users`");
$users = array();
while($row = $result->fetch_assoc()){
array_push($users, $row);
}
$res['users'] = $users;
}
if($action == 'create'){
$username = validate_input($_POST['username']);
$email = validate_input($_POST['email']);
$mobile = validate_input($_POST['mobile']);
$result = $conn->query("INSERT INTO `users` (`username`, `email`, `mobile`) VALUES ('$username', '$email', '$mobile') ");
if($result){
$res['message'] = "User added successfully";
} else {
$res['error'] = true;
$res['message'] = "Could not insert user";
}
}
if($action == 'update'){
$id = validate_input($_POST['id']);
$username = validate_input($_POST['username']);
$email = validate_input($_POST['email']);
$mobile = validate_input($_POST['mobile']);
$result = $conn->query("UPDATE `users` SET `username` = '$username', `email` = '$email', `mobile` = '$mobile' WHERE `id` = '$id'");
if($result){
$res['message'] = "User updated successfully";
} else{
$res['error'] = true;
$res['message'] = "Could not update user";
}
}
if($action == 'delete'){
$id = validate_input($_POST['id']);
$result = $conn->query("DELETE FROM `users` WHERE `id` = '$id'");
if($result){
$res['message'] = "User deleted successfully";
} else {
$res['error'] = true;
$res['message'] = "Could not delete user";
}
}
function validate_input($data) {
global $conn;
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
$data = $conn->real_escape_string($data);
return $data;
}
$conn->close();
header("Content-type: application/json");
echo json_encode($res);
die();