What are the advantages of using object-oriented programming over procedural programming in PHP when working with databases?

When working with databases in PHP, using object-oriented programming (OOP) provides several advantages over procedural programming. OOP allows for better organization and encapsulation of code, making it easier to manage database connections, queries, and results. Additionally, OOP promotes code reusability through the use of classes and objects, leading to more maintainable and scalable database operations.

// Example of using object-oriented programming in PHP to connect to a database

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 to connect and query the database

$database = new Database();
$result = $database->query("SELECT * FROM users");

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo "Name: " . $row['name'] . "<br>";
    }
} else {
    echo "No results found";
}

$database->close();