while循环里面的foreach循环里面循环[关闭]

I know just the title hurt. I feel like i'm in inception. I am using 2 different databases. I am trying to use a while loop to pick up 4 values from the first database using a while loop. Then I want to use a while loop inside a foreach loop to find the name and the related law for each of those 4 values. I have tried different codes this one gets me the closest but only returns the first value not the other three.

$link1 = mysql_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_dblogin);
if(!$link1 || !mysql_select_db ($mysql_dblogin)) {
die ($conn_error_message);
}

$link2 = mysql_connect($mysql_host, $mysql_user, $mysql_pass, $mysql_db, TRUE);
if(!$link2 || !mysql_select_db ($mysql_db)) {
die ($conn_error_message);
}



$sql="SELECT loi FROM $username";
$result = mysql_query("$sql", $link1);
$data = array();
if($result){
WHILE($row=mysql_fetch_assoc($result)){
$data[]=$row;
foreach($data as $vote){
        $loi = $vote['loi'];
        $sql="SELECT objet, colo FROM scruinfo WHERE colo = '$loi' ";
        $result=mysql_query("$sql", $link2);
        if($result){
            WHILE($row=mysql_fetch_assoc($result)){
            $loi = $row["colo"];
            $name = $row["objet"];
            echo "<table><td href='votes.php?loi=".$loi."'>".$name."</td></table><br>";
            }
        }
    }
}
}else{
echo mysql_error();
}
?>

Inside foreach you are updating $result and $row with new values, so the outer while will stop to loop.
Rename those variables and it'll work!

WHILE($row=mysql_fetch_assoc($result)){
    $data[]=$row;
    foreach($data as $vote){

This is bad, you are storing one result in data, then looping through all entities in data, then on the next loop adding another row to data and then looping all entities in data. So if you pull 10 rows from your first query, you will run the foreach on the first row 10 times, the second 9 times, the third 8 times and so on. If you pull 100 rows, you're running so many secondary loops you're going to time out, not to mention run over 5000 queries.