-1

How do I make a nested SQL loop using PHP?

I am trying to output all bundle_id's from the table packages where the row user (primary key) is $username. Inside that loop, I want to run another loop to output blacklist from the table access where bundle_id (not primary key) is the output from the first loop.

Here is my code:

$sql = "SELECT bundle_id FROM packages WHERE user='" . $username . "'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
    echo $row['bundle_id'];
    $sql = "SELECT blacklist FROM access WHERE bundle_id='" . $row['bundle_id'] . "'";
    $result = mysqli_query($conn, $sql);
    while($row = mysqli_fetch_assoc($result)){
        echo $row['blacklist'];
    }
}

The issue with my code is that it only outputs the first row from the table access.

Parsa Yazdani
  • 164
  • 1
  • 11

1 Answers1

3

You're reusing the same local variable $row and $result in both loops, which is why you're not getting the correct results. But much better, use a JOIN:

SELECT a.blacklist
FROM access a
JOIN packages p ON a.bundle_id = p.bundle_id
WHERE p.user = ?

Notice, I'm using a bind variable to prevent SQL injection / syntax errors, etc.

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509