-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.php
More file actions
182 lines (152 loc) · 5.83 KB
/
db.php
File metadata and controls
182 lines (152 loc) · 5.83 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
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
<?php
$dbConfig = [
'host' => 'localhost',
'port' => 3003,
'name' => 'Cook_book',
'user' => 'cook',
'password' => 'cook2023!book'
];
function connectToDatabase($config)
{
try {
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['name']}";
$pdo = new PDO($dsn, $config['user'], $config['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
}
$pdo = connectToDatabase($dbConfig);
fetchData();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
fetchData();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'];
// Validate the CSRF token here before processing the action
// if (isset($data['csrf_token']) && $data['csrf_token'] === $_SESSION["csrf_token"]) {
$postActions = [
'insertRecipe' => 'updateRecipe',
];
//}
}
function fetchData()
{
global $pdo;
$sqls = ['SELECT * FROM images', 'SELECT * FROM ingredients ORDER BY category'];
$data = [];
foreach ($sqls as $index => $sql) {
try {
$statement = $pdo->prepare($sql);
if ($statement->execute()) {
// Fetch data as associative array
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
// Assign the result to the corresponding key in the $data array
$data[$index] = $result;
}
} catch (Exception $e) {
// Handle exceptions and return an error response
header('Content-Type: application/json');
echo json_encode(['error' => $e->getMessage()]);
}
}
header('Content-Type: application/json');
echo json_encode($data);
exit(); // Ensure no additional output after JSON
}
function imgUpload()
{
$uploadDir = "../../uploads/";
$response = []; // Initialize the response array.
// Create the uploads directory if it doesn't exist.
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
$file_name = strip_tags($_FILES['image']['name']); //no html in filename
$targetFile = $uploadDir . basename($file_name);
// Check if the file is an actual image.
$check = getimagesize($_FILES["image"]["tmp_name"]);
if ($check !== false && $_FILES["image"]["size"] < 1000000) {
// Check if the file already exists.
if (file_exists($targetFile)) {
$response['message'] = "Erreur: Désolé, ce fichier existe déjà." . $_FILES['image']['name'];
} else {
// Move the uploaded file to the specified directory.
if (move_uploaded_file($_FILES["image"]["tmp_name"], $targetFile)) {
// Call imgToDB to insert data and get the image ID and link.
$imageInfo = imgToDB($targetFile);
if ($imageInfo) {
$response['message'] = "Succès: file " . htmlspecialchars(basename($_FILES["image"]["name"])) . " has been uploaded.";
$response['id_img'] = $imageInfo['id_img'];
$response['link'] = str_replace("../../", "../", $imageInfo['link']);
} else {
$response['message'] = "Échec de la création de l'entrée dans la base de données.";
}
} else {
$response['message'] = "Erreur: Une erreur s'est produite lors du téléchargement de votre fichier.";
}
}
} else {
$response['message'] = "Erreur: Le fichier n'est pas une image ou la taille de l'image dépasse 1 Mo.";
}
// Return the response as JSON.
header('Content-Type: application/json');
echo json_encode($response);
}
function imgToDB($targetFile)
{
try {
global $pdo;
$imageFileName = strip_tags($_FILES['file']['name']);
$imageFilePath = str_replace("../../", "../", $targetFile);
$type = "4";
$stmt = $pdo->prepare("INSERT INTO images (name, link, type) VALUES (:filename, :file_path, :type)");
$stmt->bindParam(':filename', $imageFileName);
$stmt->bindParam(':file_path', $imageFilePath);
$stmt->bindParam(':type', $type);
if ($stmt->execute()) {
// Fetch the last inserted ID.
$lastInsertId = $pdo->lastInsertId();
// Fetch the link of the last inserted ID.
$stmt = $pdo->prepare("SELECT link FROM images WHERE id_img = :lastInsertId");
$stmt->bindParam(':lastInsertId', $lastInsertId);
$stmt->execute();
$row = $stmt->fetch();
// Return an array with the image ID and link.
return ['id_img' => $lastInsertId, 'link' => $row['link']];
} else {
return null;
}
} catch (PDOException $e) {
return null;
}
}
function updateRecipe()
{
$data = json_decode(file_get_contents('php://input'), true);
$sql = '';
try {
global $pdo;
// Prepare and execute the SQL update statement
$statement = $pdo->prepare($sql);
$statement->bindParam(':lastName', $lastName);
$statement->bindParam(':firstName', $firstName);
$statement->bindParam(':email', $email);
$statement->bindParam(':rights', $rights);
$statement->bindParam(':status', $statusUser);
if (isset($userId)) {
$statement->bindParam(':userId', $userId);
}
if (!empty($password)) {
$statement->bindParam(':password', $hashedPassword);
}
if ($statement->execute()) {
$response = ['message' => 'Success : Utilisateur mis à jour avec succès.'];
}
} catch (PDOException $e) {
$response = handleError($e);
}
echo json_encode($response);
}