在我的数据库中,我有一张如下表:
现在,在我的PHP代码中,我像这样制作一个SUM:
function number_of_axless() {
$sql = "SELECT (sum(distance))/(25000)*(100) as totaldistance1 FROM axle WHERE train_id = :train_id";
$sth = $this->pdo->prepare($sql);
$sth->bindParam(':train_id', $_GET['train_id'], PDO::PARAM_STR);
$sth->execute();
return $sth->fetchAll();
}
并且:
<?php
$number_of_axles = $database->number_of_axless();
foreach($number_of_axles as $number_ofaxles){
echo $number_ofaxles['totaldistance1'];
}
?>
现在我得到了结果:40。(40%)
但我想要的是显示4个结果。有4个不同的数字。
所以:
轴1 = 0所以它应该是0%
轴2 = 2500所以它应该是10%
轴3 = 5000所以它应该是30%
轴4 = 2500所以它应该是40%
我该怎么做?
现在所有车轴都是40%。
答案 0 :(得分:0)
我会在php循环中做总结,而不是在sql中(ORDER BY子句在这里也很重要):
$sql = "SELECT distance FROM axle WHERE train_id = :train_id ORDER BY axle ASC";
...
$total_distance = 0;
foreach($number_of_axles as $number_ofaxles){
$total_distance += $number_ofaxles['distance'];
echo $total_distance/25000*100;
}