Doubt with mysqli_fetch_assoc

1

I looped using mysqli_fetch_assoc. How do I know if I'm printing the first line and the last one?

while ($dados = mysqli_fetch_assoc($query)){
    if (É A PRIMEIRA LINHA){
    echo 'imprime algo';
    }
    echo $dados['nome'];
    if (É A ULTIMA LINHA){
    echo 'imprime algo';
    }
}
    
asked by anonymous 07.02.2018 / 00:47

2 answers

2
  

The answer to your question based on your script is:

put a counter and get the number of rows 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: If there is only 1 record in the table and you do not give echo in the second if you can change the second if to if ($i!=1 && $i==$numero_de_registros){

    
07.02.2018 / 01:14
3

You do not need to know this within the loop of repetition to get this result, just remember that everything you run before the loop will always be before the first line, just as the one that runs after will be after the last line. So, you just need to do:

echo 'Antes da primeira linha';

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

echo 'Depois da última linha';

This maintains the legibility 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 that code snippet inside a if with that condition.

    
07.02.2018 / 01:30