What are the benefits of using a wrapper function for mysqli queries in PHP projects?

When working with mysqli queries in PHP projects, it is beneficial to use a wrapper function to handle common tasks such as connecting to the database, executing queries, and error handling. This simplifies the code, makes it more maintainable, and reduces the risk of SQL injection attacks.

function execute_query($query) {
    $conn = new mysqli("localhost", "username", "password", "database");

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

    $result = $conn->query($query);

    if (!$result) {
        die("Query failed: " . $conn->error);
    }

    $conn->close();

    return $result;
}

// Example usage
$query = "SELECT * FROM users";
$result = execute_query($query);

while ($row = $result->fetch_assoc()) {
    // Process each row
}

$result->free();