How can object-oriented programming principles be applied to improve the database connection handling in PHP scripts?

Database connection handling in PHP scripts can be improved by applying object-oriented programming principles such as encapsulation, inheritance, and polymorphism. By encapsulating the database connection details within a class, we can ensure better organization and reusability of code. Inheritance can be used to create a base database connection class with common methods, which can then be extended by specific database classes for different types of databases. Polymorphism allows for flexibility in switching between different database types without changing the core logic of the application.

<?php

// Database connection class using object-oriented principles
class DatabaseConnection {
    protected $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) {
        return $this->connection->query($sql);
    }

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

// Example of using the DatabaseConnection class
$db = new DatabaseConnection('localhost', 'username', 'password', 'database_name');
$result = $db->query("SELECT * FROM table_name");

// Process the query result
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
    }
} else {
    echo "0 results";
}

$db->close();

?>