How to execute two different query with single foreach in php?

by scotty_walker , in category: PHP General , 2 months ago

How to execute two different query with single foreach in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 2 months ago

@scotty_walker 

You can execute two different queries using a single foreach loop in PHP by first fetching the results of both queries and storing them in separate arrays, and then looping through both arrays in the foreach loop. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Query 1
$query1 = "SELECT * FROM table1";
$result1 = mysqli_query($connection, $query1);
$data1 = mysqli_fetch_all($result1, MYSQLI_ASSOC);

// Query 2
$query2 = "SELECT * FROM table2";
$result2 = mysqli_query($connection, $query2);
$data2 = mysqli_fetch_all($result2, MYSQLI_ASSOC);

foreach($data1 as $row1) {
    // Process data from query 1
    echo $row1['column1'];
}

foreach($data2 as $row2) {
    // Process data from query 2
    echo $row2['column1'];
}


In this example, we first fetch the results of both queries and store them in separate arrays $data1 and $data2. Then, we loop through each array in the foreach loop and process the data as needed.