Help with pg_fetch_assoc

1

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

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

$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 no_unidade field is the same on all rows. I decided to include this line before the while, 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 ready the results below. But when I do this, the first result disappears ... And they are only listed from the second on.

How do I fix it?

    
asked by anonymous 29.01.2018 / 12:36

1 answer

1

Do a do-while , eg:

$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 get information from the first line and print it as a header and before the condition is executed in while , the data of that first line is also printed.

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

Reference: do-while

    
29.01.2018 / 12:41