Grant
Grant

Reputation: 2441

Get the total from foreach loop + mysql while loop

I am getting the $_post array and running a query on each iteration, then trying to get the total points accummulated, it seems to be overwriting the total with the last point iteration. How do I fix this?

  $full_total = 0;
    foreach($postid as $key => $value){

      $array = explode(',', $value);

      if($value[0]!=''){
        $id = $array[0];
        $query = "SELECT * FROM products WHERE id = '$id'";
        $result = mysqli_query($dbc, $query);

          while ($row = mysqli_fetch_array($result)) {
            echo '<tr valign="bottom">';
            echo '<td>' . stripslashes($row['rangeCode']) . '-' . stripslashes($row['pointsType']) . '</td>';
            echo '<td>' . stripslashes($row['category']) . '</a></td>';
            echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
            echo '<td class="middle">' . stripslashes($row['points']) . '</a></td>';
            echo '</tr>';
            $total_donations = $row['points'];
          }
      }
      }
  $full_total += $total_donations;
  echo $full_total;

Upvotes: 0

Views: 235

Answers (1)

rsz
rsz

Reputation: 1161

You have to insert the $full_total in the foreach loop like this

  $full_total = 0;
foreach($postid as $key => $value){

  $array = explode(',', $value);

  if($value[0]!=''){
    $id = $array[0];
    $query = "SELECT * FROM products WHERE id = '$id'";
    $result = mysqli_query($dbc, $query);

      while ($row = mysqli_fetch_array($result)) {
        echo '<tr valign="bottom">';
        echo '<td>' . stripslashes($row['rangeCode']) . '-' . stripslashes($row['pointsType']) . '</td>';
        echo '<td>' . stripslashes($row['category']) . '</a></td>';
        echo '<td>' . stripslashes($row['itemDesc']) . '</a></td>';
        echo '<td class="middle">' . stripslashes($row['points']) . '</a></td>';
        echo '</tr>';
        $full_total += $row['points'];
      }
  }
  }
 echo $full_total;

Upvotes: 2

Related Questions