How can object-oriented programming principles be applied to improve database query functions in PHP?

To improve database query functions in PHP using object-oriented programming principles, we can create a Database class that encapsulates the connection to the database and query execution methods. This helps in better organization of code, reusability, and easier maintenance.

<?php

class Database {
    private $host = 'localhost';
    private $username = 'root';
    private $password = '';
    private $database = 'my_database';
    private $conn;

    public function __construct() {
        $this->conn = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($this->conn->connect_error) {
            die("Connection failed: " . $this->conn->connect_error);
        }
    }

    public function query($sql) {
        $result = $this->conn->query($sql);
        return $result->fetch_all(MYSQLI_ASSOC);
    }

    public function close() {
        $this->conn->close();
    }
}

// Example usage
$db = new Database();
$results = $db->query("SELECT * FROM users");
print_r($results);

$db->close();

?>