-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathphp-mysqli-factory-pattern-crud.php
285 lines (248 loc) · 8.56 KB
/
php-mysqli-factory-pattern-crud.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
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
<?php
namespace GGlink\Database;
use mysqli;
use Exception;
/**
* Class Database
*
* Provides functionalities for database interactions.
*
* @author Mokter Hossain
* @email [email protected]
* @website www.gglink.uk
* @github https://github.com/moktermd08
* @linkedin https://www.linkedin.com/in/mr-mokter/
* @twitter https://twitter.com/moGGLink
*
* @package GGlink\Database
*/
class Database
{
private string $host = "localhost"; // @var string Database host name
private string $user = "user"; // @var string Database user name
private string $password = "password"; // @var string Database password
private string $database = "database"; // @var string Name of the database to connect to
private ?mysqli $connection = null; // @var mysqli|null Database connection object
/**
* Database constructor.
*
* Initialize the Database object with the provided parameters and establish a connection.
* Connection is established immediately upon object creation.
*
* @param string $host The hostname of the MySQL server
* @param string $user The username used to connect to the MySQL server
* @param string $password The password used to authenticate the user
* @param string $database The name of the database to connect to
* @param mysqli|null $connection An existing mysqli connection object (default is null)
*
* @throws Exception If the connection to the MySQL server fails
*/
private function __construct(
private string $host,
private string $user,
private string $password,
private string $database,
private ?mysqli $connection = null
) {
$this->connect();
}
/**
* Connect to the database.
*
* @return bool true if connection is successful
* @throws Exception If connection fails
*/
public function connect(): bool
{
// Create a new mysqli object to establish a connection
$this->connection = new mysqli($this->host, $this->user, $this->password, $this->database);
// Check for connection errors and throw an exception if any
if ($this->connection->connect_error) {
throw new Exception("Failed to connect to the database: " . $this->connection->connect_error);
}
return true;
}
/**
* Disconnect from the database.
*
* @return bool true if disconnection is successful, false otherwise
*/
public function disconnect(): bool
{
// Close the existing database connection if any
if ($this->connection) {
return $this->connection->close();
}
return false;
}
/**
* Execute a generic query on the database.
*
* @param string $sql The SQL query string
* @return mixed The result of the query
* @throws Exception If the query fails
*/
public function query(string $sql)
{
// Sanitize and execute the SQL query
$result = $this->connection->query($this->sanitizeInput($sql));
// Check for query errors and throw an exception if any
if ($result === false) {
throw new Exception("Failed to execute query: " . $this->connection->error);
}
return $result;
}
/**
* Select records from a table.
*
* @param string $table The name of the table to select from
* @param string $rows The columns to select
* @param string|null $where The WHERE clause
* @param string|null $order The ORDER BY clause
* @param int|null $limit The LIMIT clause
* @return mixed The result of the select query
*/
public function select(string $table, string $rows = '*', string $where = null, string $order = null, int $limit = null)
{
// Construct the SELECT SQL query
$sql = "SELECT $rows FROM $table";
if ($where != null) {
$sql .= " WHERE $where";
}
if ($order != null) {
$sql .= " ORDER BY $order";
}
if ($limit != null) {
$sql .= " LIMIT $limit";
}
return $this->query($sql);
}
/**
* Insert records into a table.
*
* @param string $table The name of the table to insert into
* @param array $values The values to insert
* @param array|null $columns The columns to insert values into
* @return mixed The result of the insert query
*/
public function insert(string $table, array $values, array $columns = null)
{
// Construct the INSERT SQL query
$sql = "INSERT INTO $table";
if ($columns != null) {
$columns = implode(", ", $columns);
$sql .= " ($columns)";
}
$values = implode("', '", $this->sanitizeInputArray($values));
$sql .= " VALUES ('$values')";
return $this->query($sql);
}
/**
* Update records in a table.
*
* @param string $table The name of the table to update
* @param string $set The SET clause
* @param string|null $where The WHERE clause
* @return mixed The result of the update query
*/
public function update(string $table, string $set, string $where = null)
{
// Construct the UPDATE SQL query
$sql = "UPDATE $table SET $set";
if ($where != null) {
$sql .= " WHERE $where";
}
return $this->query($sql);
}
/**
* Delete records from a table.
*
* @param string $table The name of the table to delete from
* @param string|null $where The WHERE clause
* @return mixed The result of the delete query
*/
public function delete(string $table, string $where = null)
{
// Construct the DELETE SQL query
$sql = "DELETE FROM $table";
if ($where != null) {
$sql .= " WHERE $where";
}
return $this->query($sql);
}
/**
* Sanitize a single input value.
*
* @param string $data The input string
* @return string The sanitized input string
*/
private function sanitizeInput(string $data): string
{
// Trim the input, remove special HTML characters, and escape special SQL characters
return $this->connection->real_escape_string(htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8'));
}
/**
* Sanitize an array of input values.
*
* @param array $data The input array
* @return array The sanitized input array
*/
private function sanitizeInputArray(array $data): array
{
// Iterate through each value in the array and sanitize it
foreach ($data as $key => $value) {
$data[$key] = $this->sanitizeInput($value);
}
return $data;
}
}
/**
* Class DatabaseFactory
*
* Factory class to create instances of the Database class.
*
* @package GGlink\Database
*/
class DatabaseFactory
{
/**
* Create an instance of the Database class.
*
* @return Database The created Database instance
*/
public static function create(): Database
{
return new Database('localhost', 'user', 'password', 'database');
}
}
// Example use of the above classes
use GGlink\Database\Database;
use GGlink\Database\DatabaseFactory;
try {
// Create a new instance of the Database class using the DatabaseFactory
$db = DatabaseFactory::create();
// Example 1: Insert a new user into the users table
$columns = ['username', 'email', 'password'];
$values = ['john_doe', '[email protected]', 'password123'];
$db->insert('users', $values, $columns);
echo "Insert: New user added.\n";
// Example 2: Select all users from the users table
$result = $db->select('users');
echo "Select: List of all users:\n";
while ($user = $result->fetch_assoc()) {
echo "ID: " . $user['id'] . " | Username: " . $user['username'] . " | Email: " . $user['email'] . "\n";
}
// Example 3: Update the email of a specific user in the users table (e.g., user with ID 1)
$db->update('users', "email='[email protected]'", "id=1");
echo "Update: Email of user with ID 1 updated.\n";
// Example 4: Delete a specific user from the users table (e.g., user with ID 1)
$db->delete('users', "id=1");
echo "Delete: User with ID 1 deleted.\n";
} catch (Exception $e) {
// Handle exceptions (e.g., connection errors, query errors)
echo "An error occurred: " . $e->getMessage();
} finally {
// Disconnect from the database
$db->disconnect();
echo "Disconnected from the database.\n";
}