What are the advantages of using object-oriented programming (OOP) for database interactions in PHP over procedural methods?

Using object-oriented programming (OOP) for database interactions in PHP provides several advantages over procedural methods. OOP allows for better organization and encapsulation of code, making it easier to manage and maintain. It also promotes code reusability through the use of classes and objects, leading to more efficient development. Additionally, OOP allows for better error handling and scalability, making it a more robust solution for interacting with databases in PHP.

<?php
// Create a database connection class using OOP
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 close() {
        $this->connection->close();
    }
}

// Example of using the Database class
$database = new Database();
$result = $database->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
    echo "Name: " . $row['name'] . "<br>";
}
$database->close();
?>