How can OOP principles in PHP be applied to improve the structure and organization of code for handling database queries and output?

To improve the structure and organization of code for handling database queries and output in PHP, Object-Oriented Programming (OOP) principles can be applied. By creating classes for database connection, query execution, and result handling, the code can be modularized and easier to maintain. This approach also promotes code reusability and separation of concerns, leading to cleaner and more structured code.

<?php
// Database class for handling database connection
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;
    }

    public function fetchArray($result) {
        return $result->fetch_assoc();
    }

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

// Example usage
$db = new Database();
$result = $db->query("SELECT * FROM my_table");
while ($row = $db->fetchArray($result)) {
    echo $row['column_name'] . "<br>";
}
$db->close();
?>