Doubt with mysqli_fetch_assoc

Asked

Viewed 59 times

0

I made a loop using mysqli_fetch_assoc. How do I know if I’m printing the first and last lines?

while ($dados = mysqli_fetch_assoc($query)){
    if (É A PRIMEIRA LINHA){
    echo 'imprime algo';
    }
    echo $dados['nome'];
    if (É A ULTIMA LINHA){
    echo 'imprime algo';
    }
}
  • What should happen if the first and last lines are the same, ie when there is only one record?

2 answers

2


The answer to your question based on your script is:

place a counter and get the number of lines of the result:

$numero_de_registros = mysqli_num_rows($result);
$i=1;
while ($dados = mysqli_fetch_assoc($query)){  

    if ($i==1){
    echo 'imprime algo';
    }

    echo $dados['nome'];

    if ($i==$numero_de_registros){
    echo 'imprime algo';
    }
    $i++;
}

mysqli_num_rows - Get the number of rows in a result

NOTE: In case there is only 1 (one) record in the table and not give echo in the second if can change the second if for if ($i!=1 && $i==$numero_de_registros){

2

You don’t need to know this inside the loop to get that result, just remember that everything you perform before the loop will always be before the first line, just like what runs after it will be after the last line. So just do it:

echo 'Antes da primeira linha';

while ($dados = mysqli_fetch_assoc($query)){
    echo $dados['nome'];
}

echo 'Depois da última linha';

This maintains the readability of the code and avoids having to evaluate two logical expressions at each loop. If you want to prevent messages from appearing when there are no records, just place this code snippet inside a if on such condition.

  • if there are no results will give 2 Sets for nothing.

  • @Leocaracciolo commented on this in the last sentence of the reply...

  • it is true, mania of just look at the code! reverti o voto rs!

Browser other questions tagged

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