从循环中获取foreach循环+ mysql的总数

时间:2013-03-07 14:51:51

标签: php mysql

我正在获取$ _post数组并在每次迭代时运行查询,然后尝试获得累积的总点数,它似乎是在最后一次迭代时覆盖总数。我该如何解决这个问题?

  $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;

1 个答案:

答案 0 :(得分:2)

您必须像这样

在foreach循环中插入$full_total
  $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;