PHP While generating more loop

Asked

Viewed 89 times

0

My while is inventing a count more. Why that?

$rsMsgLer = $conexao->query("SELECT * FROM mensagens WHERE para = '".$row['ID_Cadastro']."' GROUP BY de");

.

<?php do { ?>

...

<?php } while ($rowMsgLer = $rsMsgLer->fetch_assoc()); ?>

Should appear only 3 records:

inserir a descrição da imagem aqui

but this listing 4, one is some mistake:

inserir a descrição da imagem aqui

  • 1

    Because the do...while executes the code block before checking the condition and you only recover the record in condition. That is, the first time it is executed, there is no record to be displayed. Change the do...while for while and see if it works.

  • @Andersoncarloswoss It worked, thank you.

  • @Andersoncarloswoss Why not put as an answer to receive score?

1 answer

3


The problem is using the structure do ... while to iterate on the record. Considering the code below:

do {

    <block>

} while (<condition>);

The code block defined in <block> will be executed before the condition <condition> be checked. As in your problem, the condition is an assignment of the database record to the variable $rowMsgLer, in the first iteration of this loop, this variable will not exist, generating the error shown. To correct, just switch to the structure while:

while (<condition>) {

    <block>

}

Thus, the condition will be checked before the code block is executed and therefore already in the first loop iteration, the variable will be properly $rowMsgLer definite.

Browser other questions tagged

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