Using while inside while in PHP

Asked

Viewed 2,189 times

6

What happens in my PHP code is the following: I make a query in the database and with it a DO WHILE (while this query returns records), it displays some information on the screen (based on the query, of course). So far, everything is fine. However, I need now, within this DO WHILE, put another, to go through another query and 'printar' other values. I need this inside another WHILE DO 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 did not rotate 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));
  • 1

    What your query of $dados returns? Add the queries sql what you do.

  • Adds the entire code.

  • Good day friend , post here the codes of your 2 queries . One while inside another I particularly do not recommend . In case ,I believe that making a Join between the tables would be better.

  • If I understand your doubt well you intend to use a while inside another to be able to query two distinct tables that have related id’s right? If so, I believe that the best alternative instead of using multiple whiles would be to use "Joins" directly in your SQL: What is the difference between INNER JOIN and OUTER JOIN? Good Luck!

  • Iterate one query into another? Just ... don’t ... do ..... it ....

1 answer

1

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

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

In place of

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

For using do .. while, the loop is executed at least once, which can generate error if the query does not return anything. Moreover it is necessary to execute $consulta = mysql_fetch_assoc($dados) before the do to ensure that there will be some value in the variable $consulta.

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 lousy in terms of performance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.