Nested Loops AND SQL

Hello,

My question is regarding SQL and PHP. Specifically, nesting a loop inside another loop that both grab information from the server. I’m unsure if I’m going about this the right way.

Essentially, for every row of data from table 1, I want to check if a value matches from both tables in column 1, and if it does, grab that whole matching row(or multiple rows) from table two and insert that below each consecutive row from table one as the function iterates through.

My code is something like this;

$table1 = “SELECT * FROM table1”;
$table2 = “SELECT * FROM table2”;

$query_table1 = $link-> query($table1);
$query_table2 = $link-> query($table2);

while ($table1_data = $table1 → fetch_assoc()) {
echo $table1_data;
while ($table2_data = $table2 → fetch_assoc()) {
if ($table2_data[“col1_data”] === $table1_data[“col1_data”]) {
echo $table2_data;
}
}
}

The result is that I get all the output from table 1, then nothing from table 2.
If I remove the if, I get row 1 table 1, then all of table 2, then the rest of table 1.

Any hints are appreciated and apologies for missing any of the guidelines.

Thank you.

Whatever your doing your approach is wrong. There should be no need whatsoever to move data between tables. Look up and learn about “Database Normalization”.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service