Search code examples
phparraysloops

Make iterated trips to the database based on a parent query


<?php
        
session_start();
$link = mysqli_connect("localhost", "xxx", "xxxxxx", "xxx");
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$id = $_GET['id'];
if ($result = mysqli_query($link, "SELECT * FROM Subscribe WHERE STo = '".$id."' ORDER BY ID LIMIT 6")) {
    while($row = mysqli_fetch_array($result))
    {
        $idS = $row['SWho'];
        echo $idS;
        if ($result = mysqli_query($link, "SELECT * FROM accounts WHERE ID = '".$idS."' ORDER BY ID LIMIT 6")) {
            while($row = mysqli_fetch_array($result))
            {
                echo "<img src='Member_ProfilePics/";
                echo $row['PP'] . '.' . $row['Ext'];
                echo "' width=42 height=40 style='float: left'>";
            }
        }
    }
    //<img src='Member_ProfilePics/john.jpg' width=42 height=40 style='float: left'>
}                               
?>

Here in my code, I want to output the list of STo. and connect to other database and output the following rows in each STo.

Sample to be output:

(picture of id=1) 1 
(picture of id=2) 2 
(picture of id=3) 3 
(picture of id=4) 4 
(picture of id=5) 5 
(picture of id=6) 6

How? my code is not looping.

Sample output of my code:

(picture of id=1) 1

Solution

  • You are using the same variables for both the loops:

    if ($result = mysqli_query($link, "SELECT * FROM Subscribe WHERE STo = '".$id."' ORDER BY ID LIMIT 6")) {
        while($row = mysqli_fetch_array($result)) {
    
            ....
    
            if ($result = mysqli_query($link, "SELECT * FROM accounts WHERE ID = '".$idS."' ORDER BY ID LIMIT 6")) {
                while($row = mysqli_fetch_array($result)) {
                    ...
                }
            }
        }
    } 
    

    Try to change the seconda value to these

    if ($result = mysqli_query($link, "SELECT * FROM Subscribe WHERE STo = '".$id."' ORDER BY ID LIMIT 6")) {
        while($row = mysqli_fetch_array($result)) {
    
            ....
    
            if ($result2 = mysqli_query($link, "SELECT * FROM accounts WHERE ID = '".$idS."' ORDER BY ID LIMIT 6")) {
                while($row2 = mysqli_fetch_array($result2)) {
                    ...
                }
            }
        }
    }