我得到了一个查询代码,它从数据库中获取所有数据,这是我的数据库中的int,然后我使用同时获得所有数据,然后声明一个总变量,它将显示总价值。为了前夫。我的数据库中有5和2,所以输出应该是7,但是输出是52,这是作为文本而不是int添加的。
<?php
$st='SELECT rating FROM rating;';
$t=mysqli_stmt_init($conn);
mysqli_stmt_prepare($t,$st);
mysqli_stmt_execute($t);
$res=mysqli_stmt_get_result($t);
while($rop=mysqli_fetch_assoc($res)){
$total=0;
$total+=$rop['rating'];
echo $total;
}发布于 2019-03-08 09:22:02
您可以直接使用MySQL的SUM()函数:
SELECT sum(rating) as total from rating此查询将直接给出所有列值的和。
因此,最终代码应该是:
$st='SELECT sum(rating) as total from rating';
$t=mysqli_stmt_init($conn);
mysqli_stmt_prepare($t,$st);
mysqli_stmt_execute($t);
$res=mysqli_stmt_get_result($t);
$total=0;
while($rop=mysqli_fetch_assoc($res)){
$total = $rop['total'];
}
echo $total;发布于 2019-03-08 09:22:43
将查询更改为
$st='SELECT rating FROM rating;';至
$st='SELECT sum(rating) as total_sum FROM rating;';也变了
while($rop=mysqli_fetch_assoc($res)){
$total=0;
$total+=$rop['rating'];
echo $total;
}至
$total = mysqli_fetch_assoc($res)['total_sum'];
echo $total;https://stackoverflow.com/questions/55060078
复制相似问题