Successfully connected to my database. I have a table like,
stid | date | bf | ln | dn | meal_total
------------------------------------------------------
01 | 2015-11-27 13:12:01 | 1 | 2 | 3 | 6
01 | 2015-11-27 11:12:01 | 0 | 3 | 2 | 5
02 | 2015-11-27 12:12:01 | 1 | 1 | 1 | 3
03 | 2015-11-27 11:12:01 | 1 | 1 | 1 | 3
I just need to echo
the SUM
of all the values of the meal_total
column recorded in current month
for a stid
like,
Total Meal for `stid` in current month : 11.
I am trying this code like,
$sql = "select sum(meal_total)
from meal
where stid='$_SESSION[stid]'
AND date >= DATE_ADD(CURDATE(), INTERVAL -DAY(CURDATE())+1 DAY) ";
And I am trying to show the result in a html table like,
<? php
echo sum(meal_total);
?>
Now, Sir, please help me to solve. Thanks in advance.
[I have tried my best to clarify my problem.]
Since you didn't provide any valid PHP code, I'm just going to guess that you don't know how to access the SUM
field from the result set.
When you SELECT SUM(meal_total)
you should alias the field in order to access it from your PHP result array like so SELECT SUM(meal_total) AS meal_sum
and you can echo $resultArray['meal_sum']
to get the value in question.
您需要在查询中使用Group by语句: http : //dev.mysql.com/doc/refman/5.7/en/group-by-functions.html
If you name your result, you can get it from your results a bit easier. I suggest that you use DATE_FORMAT , which lets you easily compare parts of dates.
$sql = "select sum(meal_total) AS meals
from meal
where stid='$_SESSION[stid]'
AND DATE_FORMAT( `date`, '%Y-%m' ) = DATE_FORMAT( NOW(), '%Y-%m' )";
# get result from sql
...
#
echo $result['meals'];
Offtopic: Even though I am a 'Sir', please beware that there are many (great) female programmers aswel.
Try
select
m.stdid,
sum(m.meal_total) as month_meals
from
meal as m
where
year(m.date)= year(month(CURRENT_DATE())
AND
month(m.date) = month(month(CURRENT_DATE())
group by m.stdid
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.