How can the error "query() on a non-object" be resolved in the PHP code?

The error "query() on a non-object" occurs when the query() method is called on a variable that is not an object, typically due to a failed database connection. To resolve this error, make sure that the database connection is successfully established before calling the query() method.

// Check if the database connection is successful before executing the query
if ($connection instanceof mysqli) {
    $result = $connection->query("SELECT * FROM table_name");
    // Rest of the code to process the query result
} else {
    echo "Database connection failed.";
}