我想做的是打印一张表,并在每一行中打印,对于DB中的每个不同值,该值,具有该值的DB中的行数以及这些值的总和。不好意思,这没有很好的表达,更容易直接进入代码

$query_voucher1="SELECT * FROM voucher WHERE consegnato= 0 AND IDprestazione=0 ORDER BY codice";
$risultato_query_voucher1=@mysql_query($query_voucher1);
echo "<table class='table table-striped' style='margin-top:70px; width: 60%;'>
      <caption>Riassunto Voucher Liberi</caption>
       <tr>
         <th>Codice di controllo</th>
         <th>Quantità (solo liberi)</th>
         <th>Data Emissione</th>
         <th>Valore Pacchetto (solo liberi)</th>
        </tr>";

$prevcodice= NULL;
$curcodice= 10;
while ($row_voucher1=mysql_fetch_row($risultato_query_voucher1)) {
                if ($curcodice!=$prevcodice){
                  $array_temp_query_value=array();
                  if ($modifica==true){
                  $temp_query_value=mysql_query("SELECT valorelordo FROM voucher WHERE codice='$row_voucher1[2]' AND consegnato=0 ");
                  }else{
                    $temp_query_value=mysql_query("SELECT valorelordo FROM voucher WHERE codice='$row_voucher1[2]' AND consegnato=0 AND IDprestazione=0");
                  }
                  while(mysql_fetch_row($temp_query_value)){
                    array_push($array_temp_query_value, $temp_query_value[0]);
                  }
                  echo "<tr>
                          <td>" . $row_voucher1[2] . "</td>
                          <td>" . count($array_temp_query_value) . "</td>
                          <td>" . print_r($array_temp_query_value). "</td>
                        </tr>";
                  $prevcodice=$row_voucher1[2];

                }
              $curcodice=$row_voucher1[2];
              }

              echo "</table>";


因此,假设我有一个具有字段codice的数据库,并且该字段中的许多值都是重复的。我想做的是打印一次值,一次codice相同的行数,一次一次codice相同的值之和。

这种解释也不是很好,所以在这里JSFiddle

$array_temp_query_value返回正确数量的值,因此我可以对它们进行计数以填充第二个字段,但是数组中的所有值均为空,因此我无法对它们求和。查询看起来不错,所以我真的不知道。

最佳答案

您无需自己计算该值,只需使用count()sum()group by,例如

select codice, count(*), sum(codice)
from voucher
group by codice


这将为您提供表中的所有现有值,每个值的行数以及总和。



预先,不要使用mysql_*函数,因为它们是deprecated并已在PHP 7中删除。

使用mysqli(取自mysqli_fetch_row的在线手册),遵循以下原则(未经测试)

$result = mysqli_query($conn, 'select codice, count(*), sum(codice) from voucher group by codice');
while ($row = mysqli_fetch_row($result)) {
    echo '<tr><td>' . $row[0] . '</td><td>' . $row[1] . '</td><td>' . $row[2] . '</td></tr>';
}

10-05 20:17