What are the potential benefits of using a wrapper class for database communication in PHP?
When communicating with a database in PHP, it is important to handle errors, connections, and queries consistently. Using a wrapper class can help encapsulate database operations, making the code more modular, readable, and maintainable. It can also provide an additional layer of security by implementing proper input sanitization and preventing SQL injection attacks.
<?php
class DatabaseWrapper {
private $connection;
public function __construct($host, $username, $password, $database) {
$this->connection = new mysqli($host, $username, $password, $database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
public function query($sql) {
$result = $this->connection->query($sql);
if (!$result) {
die("Query failed: " . $this->connection->error);
}
return $result;
}
public function sanitizeInput($input) {
return $this->connection->real_escape_string($input);
}
public function close() {
$this->connection->close();
}
}
// Example of using the DatabaseWrapper class
$database = new DatabaseWrapper("localhost", "username", "password", "database_name");
$sql = "SELECT * FROM users";
$result = $database->query($sql);
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row['name'] . "<br>";
}
$database->close();
?>
Related Questions
- Are there any specific PHP functions or methods that can be used to check if a checkbox is empty or not?
- How can the extension_dir parameter in the php.ini file be configured to properly load the php_gd2.dll file in an Apache/Windows setup?
- What are the potential pitfalls of using ASCII characters instead of UTF-8 characters in PHP regex patterns?