I have a problem making two different nested SQL queries. While I’m echoing the results of the first one I would like to execute a second query based on some condition. The problem is that, when I execute the second query, the first one stops and the rest of the while loop is skipped.
Here is how the code looks like:
$sql = "SELECT * FROM table1 WHERE conditions";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result)) {
.
.
.
echo '<td>' . $row['column1'] . '</td>';
.
.
.
if (a condition is true) {
echo '<td>' . $row['column_k'] . '</td>';
} else {
$x = $row['column_k'];
$conn1 = mysqli_connect('localhost', 'root', 'root', 'database'); // the same database of $conn
$sql1 = "SELECT name
FROM table2
WHERE boss = '$x'";
$result1 = mysqli_query($conn1,$sql1);
while ($row = mysqli_fetch_array($result1)) {
$boss = $row['boss'];
}
echo '<td>Some different text here ' . $boss . '</td>';
}
echo '<td>' . $row['column_k+1'] . '</td>';
.
.
.
echo ...
} //while*/
When the condition is true everything works correctly: everything after the if then else statement is correctly echoed.
The problem appears when the condition is false (when the second query is executed). Everything works correctly until the if then else statement, the last echo instruction that works is this one:
echo '<td>Some different text here ' . $boss . '</td>';
All the other echo instruction are not executed. This makes me think that there is a problem with how I set up the database connections, somehow the second one interferes with the first one. At least this is what I think, but I can’t understand how to fix this.