我想做的是打印一个表,并在每一行中打印,对于数据库中的每个不同值,值,数据库中具有该值的行数以及值的总和。对不起,这没有很好地解释,更容易直接进入代码
$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>';
}
关于PHP - 嵌套递归 SQL 查询不检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315502/