How can one avoid the "Invalid argument supplied for foreach()" error in PHP when querying multiple tables with the same prefix?

When querying multiple tables with the same prefix in PHP, you may encounter the "Invalid argument supplied for foreach()" error if the query does not return any results. To avoid this error, you should check if the result of the query is not empty before attempting to iterate over it using a foreach loop. This can be done by verifying if the result is not false or null.

// Perform the query
$result = $wpdb->get_results("SELECT * FROM wp_posts WHERE post_type = 'post'");

// Check if the result is not empty before using foreach
if($result !== false && $result !== null) {
    foreach($result as $row) {
        // Process each row here
    }
} else {
    // Handle the case when the query returns no results
}