How can developers avoid errors like "Trying to get property 'num_rows' of non-object" when querying databases in PHP?

To avoid errors like "Trying to get property 'num_rows' of non-object" when querying databases in PHP, developers should check if the query was successful before trying to access properties like 'num_rows'. This can be done by verifying if the query returned a valid result object before attempting to access its properties.

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

// Check if the query was successful
if ($query) {
    // Access the 'num_rows' property only if the query was successful
    $num_rows = $query->num_rows;
    
    // Process the query results
    while ($row = $query->fetch_assoc()) {
        // Do something with the data
    }
} else {
    // Handle the case where the query was not successful
    echo "Error executing query: " . $mysqli->error;
}