Help with pg_fetch_assoc

Asked

Viewed 46 times

1

I have the variable $result that returns me the result of a query.

I do a while on it and get all the information:

$total = 0;
while ($row = pg_fetch_assoc($result)) {
  echo "<tr><td>".$row['no_unidade']."</td><td>".$row['no_pessoa_fisica']."</td><td style='text-align:right;'>".$row['count']."</td></tr>";
  $total += $row['count'];
}

Since the field no_unidade is the same on all lines. I decided to include that line before the while, getting so:

$row= pg_fetch_assoc($result);

echo '<h1 style="text-align:center;">'.$row['no_unidade'].'</h1>';

$total = 0;
  while ($row = pg_fetch_assoc($result)) {
    echo "<tr><td>".$row['no_unidade']."  </td><td>".$row['no_pessoa_fisica']."</td><td style='text-align:right;'>".$row['count']."</td></tr>";
  $total += $row['count'];
}

So I add the line that repeats at the top and list the results below. However, when I do, the first result goes... And are only listed from the second onwards.

How do I fix?

1 answer

1


Make a do-while, example:

$row = pg_fetch_assoc($result);

echo '<h1 style="text-align:center;">'.$row['no_unidade'].'</h1>';

$total = 0;

do 
{
      echo "<tr><td>".$row['no_unidade']."  
          </td><td>".$row['no_pessoa_fisica']."
          </td><td style='text-align:right;'>".$row['count']."</td></tr>";

      $total += $row['count'];

} while ($row = pg_fetch_assoc($result));

This structure in your specific case is ideal, because you need to take information from the first line and print as a header and before the condition on while also printed the data of this first line.

Here on the site already has an explanation: What’s the difference between while, for, while and foreach?, good reading.

Reference: do-while

  • it worked. you can explain to me why it works?

  • 1

    @Italorodrigo made an edit and put what happens, is that in this case the condition only executed after the first execution, different from your while that before entering the while is made a check ...

  • 1

    @Italorodrigo got it?

  • I understood yes, very well explained. Hug

Browser other questions tagged

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