-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
92 lines (66 loc) · 2.32 KB
/
functions.php
File metadata and controls
92 lines (66 loc) · 2.32 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
<?php
// ===== functions.php =====
include 'config.php';
// Function to validate student data
function validateStudentData($data) {
$errors = [];
if (empty($data['first_name'])) {
$errors[] = "First name is required";
}
if (empty($data['last_name'])) {
$errors[] = "Last name is required";
}
if (empty($data['email'])) {
$errors[] = "Email is required";
} elseif (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}
if (empty($data['phone'])) {
$errors[] = "Phone number is required";
} elseif (!preg_match('/^[0-9]{10,15}$/', $data['phone'])) {
$errors[] = "Phone number must be 10-15 digits";
}
return $errors;
}
// Function to register student
function registerStudent($conn, $data) {
$errors = validateStudentData($data);
// print_r($data); exit(); // for debugging (1)
$first_name = mysqli_real_escape_string($conn, $data['first_name']);
$last_name = mysqli_real_escape_string($conn, $data['last_name']);
$email = mysqli_real_escape_string($conn, $data['email']);
$phone = mysqli_real_escape_string($conn, $data['phone']);
if (!empty($errors)) {
return ['success' => false, 'errors' => $errors];
}
$sql = "INSERT INTO students (first_name, last_name, email, phone)
VALUES ('$first_name', '$last_name', '$email', '$phone')";
// echo($sql); exit();
$exQuery = mysqli_query($conn, $sql);
// print_r($exQuery);
// exit(); //for debugging
if ($exQuery) {
$res = ['status' => true,'message' => 'Student registered successfully'];
return $res;
// echo json_encode($res);
exit();
} else {
$res = ['status' => false, 'errors' => ['Database error: ' . mysqli_error($conn)]];
return $res;
// echo json_encode($res); exit();
}
}
// Function to get all students
function getAllStudents($conn) {
$sql = "SELECT * FROM students ORDER BY last_name, first_name";
$result = mysqli_query($conn, $sql);
$students = [];
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$students[] = $row;
}
}
// print_r($students); exit(); // for debugging (3)
return $students;
}
?>