如何计算查询 PHP MySQL 中的行? [英] How to calculate rows in query PHP MySQL?
问题描述
我必须在数据库中查询 2 行 sum_hour(double type)
I have to 2 rows of query of sum_hour(double type) in database
第一行 = sum_hour = 2.75
1st row = sum_hour = 2.75
第二行 = sum_hour = 3.00
2nd row = sum_hour = 3.00
它属于 type_move = 'P' 和 (开始日期 >= 2016-11-11 AND end_date <= 2016-11-15)的 2(两个)组 组.代码如下:
It belongs inside 2(two) groups which is type_move = 'P' and (start date >= 2016-11-11 AND end_date <= 2016-11-15) group. The code as below :
<?php
$sql = "SELECT sum_hour,
SUM(sum_hour)
FROM table
WHERE type_move = 'P' AND user_id='username' AND (start_date >= '2016-11-11' AND end_date <= '2016-11-15')
GROUP BY sum_hour ";
$result = mysqli_query($connect, $sql);
if($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$hour = $row['sum_hour'];
echo " Hours = " .$hour. "<br/>";
print_r($row);
}
echo "Total hours = " .$hour. "<br/>";
mysqli_free_result($result);
}
else
{
echo mysqli_error($connect);
}
?>
输出如下:
小时数 = 2.75
小时数 = 3.00
总小时数 = ?
我的问题是,如何计算上面的 2 行(小时)? 我试图在 phpmyadmin 中运行 sql 语句.它有效,我可以看到总和为 = 5.75,但我不知道如何在浏览器中回显总数
My question is , how to calculate 2 rows (Hours) above ? I tried to run sql statement in phpmyadmin. It work and i can see the value sum up into = 5.75 but i don't know how to echo the total in browser
谢谢.
推荐答案
只需更新您的循环:
$totalHours = 0;
while($row = mysqli_fetch_assoc($result))
{
$hour = $row['sum_hour'];
$totalHours += $hour;
echo " Hours = " .$hour. "<br/>";
print_r($row);
}
echo "Total hours = " .$totalHours. "<br/>";
您需要将第一个值存储在一个变量中,然后将第二个值与第一个值相加.只需确保可以在循环外读取该值.
You need to store the first value in a variable then add the second one to the first value. Just make sure that the value can be read outside the loop.
这篇关于如何计算查询 PHP MySQL 中的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!