How can object-oriented programming principles be applied effectively in PHP for database connections?

To apply object-oriented programming principles effectively in PHP for database connections, you can create a separate class specifically for handling database connections. This class can encapsulate the connection details and provide methods for executing queries and fetching results. By using this class, you can ensure a more organized and maintainable approach to interacting with databases in your PHP applications.

<?php

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

    public function __construct() {
        $this->connection = new mysqli($this->host, $this->username, $this->password, $this->database);

        if ($this->connection->connect_error) {
            die("Connection failed: " . $this->connection->connect_error);
        }
    }

    public function query($sql) {
        return $this->connection->query($sql);
    }

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

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

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

?>