-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate.php
More file actions
79 lines (59 loc) · 1.9 KB
/
Copy pathcreate.php
File metadata and controls
79 lines (59 loc) · 1.9 KB
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
<?php
include 'dbconnection.php';
$json = file_get_contents('php://input');
$data = json_decode($json);
$titleValue = filter_var($data->title, FILTER_SANITIZE_STRING);
$authorValue = filter_var($data->author, FILTER_SANITIZE_STRING);
$messagesValue = filter_var($data->messages, FILTER_SANITIZE_STRING);
$status = [
"status" => "success",
"notes" => [],
];
$errors = [];
//validate
if ($titleValue == "" || $titleValue == null) {
$errors['title'] = "title is empty";
}
if ($authorValue == "" || $authorValue == null) {
$errors['author'] = "author is empty";
}
if ($messagesValue == "" || $messagesValue == null) {
$errors['messages'] = "messages is empty";
}
if (!empty($errors)) {
$status['status'] = "error";
$status['errors'] = $errors;
echo json_encode($status);
die;
}
try{
$sql = "INSERT INTO notes (title, author, messages) VALUES (:title, :author, :messages)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':title', $title, PDO::PARAM_STR);
$stmt->bindParam(':author', $author, PDO::PARAM_STR);
$stmt->bindParam(':messages', $messages, PDO::PARAM_STR);
$title = $titleValue;
$author = $authorValue;
$messages = $messagesValue;
$stmt->execute();
$status['message'] = "note successfully created";
} catch(PDOException $e){
die("ERROR: Could not prepare/execute query: $sql. " . $e->getmessages());
}
try {
$sql = "SELECT * FROM notes ORDER BY id ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$notes = $stmt->fetchAll();
foreach ($notes as $note) {
array_push($status['notes'], [
'id' => $note['id'],
'title' => $note['title'],
'author' => $note['author'],
'messages' => $note['messages'],
]);
}
echo json_encode($status);
} catch (PDOException $e) {
die("ERROR: Could not prepare/execute query: $sql. " . $e->getmessages());
}