Use of while within another while in PHP

6

What happens in my PHP code is this: I make a query in the database and with that a DO WHILE (while that query returns records), it displays some information on the screen (based on the query, of course). Until then, all right. However I need now, within this DO WHILE, to place another, to go through another query and 'start' other values. I need this within another DO WHILE why the new query will always be according to the ID generated in the first query, that is, different for each iteration. Tests in different ways but did not run or get error. How can I have a "while" and within this, after the "do", have another?

Ex:

do{

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

while($consulta = mysql_fetch_assoc($dados));
    
asked by anonymous 24.11.2015 / 23:57

1 answer

1

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

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

Instead of

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

Because using do .. while , the loop is executed at least once, which can generate error if the query returns nothing. It is also necessary to execute $consulta = mysql_fetch_assoc($dados) before do to ensure that it will have 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, you will run the internal loop 15 times, getting poor performance.

    
30.11.2015 / 20:54