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();

?>