Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

PHP Double While Loops

Using while loops, you can extract rows of data for which you and create variables with the results. Afterwards, you can use the variables to sort through more data. When sorting through databases, you can write single queries to obtain rows from one or more tables.

From time to time, you may find you need a large query to obtain the data you want. In this case, using joins is the way to go. But, the next two examples show has one query is used to capture ids from the first table. Then, the ids are used to select a url if the member_id exists in the second table. Again, this is spotting issues rather than recommending as a procedure.

Example#1

<?php require_once(‘dbconnect.inc’);
$db=dbconnect();
$start = microtime(true);

$command= ‘SELECT id FROM table_sort ‘;
$result = mysqli_query($db, $command);

while($row = mysqli_fetch_assoc($result)) {
$id = $row[‘id’];

$command2= “SELECT url FROM members_urls WHERE member_id=’$id’ “;
$result2 = mysqli_query($db, $command2);
while($row = mysqli_fetch_assoc($result2)) {
$url = $row[‘url’];
echo $url.'<br/>’;
}

}

Example #2

This example shows how an array can be made with the second while loop. Then, the array is pulled outside the loop and individual values are printed.

<?php require_once(‘dbconnect.inc’);
$db= dbconnect();
$start = microtime(true);

$command= ‘SELECT id FROM table_sort ‘;
$result = mysqli_query($db, $command);

while($row = mysqli_fetch_assoc($result)) {
$id = $row[‘id’];

$command2= “SELECT url FROM members_urls WHERE member_id=’$id’ “;
$result2 = mysqli_query($db, $command2);
while($row = mysqli_fetch_assoc($result2)) {
$url = $row[‘url’];
$url_array[] = $url;

}
}

$url_array = array_unique($url_array);
//print_r($url_array);

foreach($url_array as $item) {
echo $item.'<br/>’;
}