When handling database connections in PHP, what are some common best practices to avoid errors like "Call to a member function fetch() on a non-object"?

When handling database connections in PHP, it is important to check if the query execution was successful before attempting to fetch results. This error commonly occurs when the query fails and returns a non-object instead of a result set. To avoid this error, always verify the query execution status before fetching data.

// Establish database connection
$connection = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare and execute query
$query = $connection->prepare("SELECT * FROM users");
$query->execute();

// Check if query execution was successful
if($query) {
    // Fetch results
    $results = $query->fetchAll(PDO::FETCH_ASSOC);
    
    // Process results
    foreach($results as $result) {
        // Do something with the data
    }
} else {
    echo "Error executing query.";
}