Using do while inside another do while in PHP

Question:

What happens in my PHP code is the following: I make a query in the database and with that a DO WHILE (while this query returns records), displays some information on the screen (based on the query, of course). Until then, all is well. But I need now, inside this DO WHILE, to put another one, to go through another query and 'print' other values. I need this inside another DO WHILE because the new query will always be according to the ID generated in the first query, that is, different for each iteration. Tests in several ways but it didn't run or I got an error. How can I have a "do while" and inside it, after the "do", have another one?

Ex:

do{

      do{
      while($consulta2 = mysql_fetch_assoc($dados2));

while($consulta = mysql_fetch_assoc($dados));

Answer:

Your ties are correct. Perhaps the error occurs because you are using

do {
    // Código
} while( ... );

not place of

while( ... ) {
    // Código
}

Because using do .. while , the loop is executed at least once, which can generate an error if the query does not return anything. Also, you need to run $consulta = mysql_fetch_assoc($dados) before do to ensure that there will be some value in the $consulta variable.

I recommend changing your code to

while($consulta = mysql_fetch_assoc($dados)) {
    // Código
    while($consulta2 = mysql_fetch_assoc($dados2)) {
        // Código
    }
}

When you add a while inside the other you increase the processing exponentially.

Ex: if you have 15 records, it will execute the internal loop 15 times, getting bad in terms of performance.

Scroll to Top