How can a foreach loop be executed only if data is returned after a JOIN query in PHP?

To execute a foreach loop only if data is returned after a JOIN query in PHP, you can check if the result set is not empty before iterating through it. This can be done by using the rowCount() method on the result set object returned by the query execution. If the rowCount() method returns a value greater than 0, it means that data has been returned and the foreach loop can be executed.

// Execute JOIN query
$query = "SELECT * FROM table1 JOIN table2 ON table1.id = table2.table1_id";
$result = $pdo->query($query);

// Check if data is returned before executing foreach loop
if ($result->rowCount() > 0) {
    foreach ($result as $row) {
        // Process each row of data
    }
} else {
    echo "No data returned from JOIN query.";
}