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

When working with mysqli in PHP, using the object-oriented approach provides several advantages over the procedural approach. Object-oriented programming allows for better organization of code, reusability of objects, and encapsulation of data and behavior. Additionally, it promotes code readability and maintainability, making it easier to work with complex database operations.

// Object-oriented approach using mysqli in PHP
$mysqli = new mysqli("localhost", "username", "password", "database");

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

// Perform query
$sql = "SELECT * FROM table";
$result = $mysqli->query($sql);

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

// Close connection
$mysqli->close();