-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert_data.php
97 lines (80 loc) · 2.93 KB
/
insert_data.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
<?php
function insert($tableName, $data, $rules = [], $successMsg = 'Data inserted successfully.') {
global $connect;
$columns = implode(", ", array_keys($data));
$placeholders = ":" . implode(", :", array_keys($data));
$sql = "INSERT INTO $tableName ($columns) VALUES ($placeholders)";
$stmt = $connect->prepare($sql);
foreach ($data as $key => $value) {
$stmt->bindValue(":$key", $value);
}
// Check validation rules for specific fields
$errors = []; // initialize empty array to store errors
foreach ($rules as $field => $fieldRules) {
foreach ($fieldRules as $rule => $param) {
if ($rule === 'required') {
if ($param && empty($data[$field])) {
$errors[$field] = "$field is required.";
}
} else if ($rule === 'min') {
if (strlen($data[$field]) < $param) {
$errors[$field] = "$field must be at least $param characters long.";
}
} else if ($rule === 'max') {
if (strlen($data[$field]) > $param) {
$errors[$field] = "$field cannot be more than $param characters long.";
}
}
}
}
// Check if there are errors
if (!empty($errors)) {
return $errors; // return array of errors
}
try {
$stmt->execute();
return $successMsg;
} catch (PDOException $e) {
return "Error: " . $e->getMessage();
}
}
// Example usage:
$register_user_data = array(
'name' => $name,
'email' => $email,
'username' => $username,
'password' => $user_encrypted_password,
'role' => $role,
'contact' => $contact,
'activation_code' => $activation_code,
'email_status' => 0,
'user_status' => 0
);
$register_user_rules = array(
'name' => array('required' => true, 'min' => 3, 'max' => 20),
'email' => array('required' => true, 'min' => 5, 'max' => 25),
'username' => array('required' => true, 'min' => 3, 'max' => 20)
);
$result = array();
if(!empty($email)){
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$result[] = "Invalid email";
}
}
else{
$result[] = "Email is required";
}
$result = insert('user', $register_user_data, $register_user_rules, 'Successfully Register');
$alert = '';
$alert_message = '';
if (is_array($result)) {
foreach ($result as $error) {
$alert_message .= $error . '<br>';
$alert = 'danger';
}
} else {
$alert = 'success';
$alert_message = $result;
}
$attempt_alert = "<div class='alert alert-$alert' style='text-align:center;'>$alert_message</div>";
?>