[英]For each / query doesn't give the right value
I have a table in my database. 我的数据库中有一个表。 I want to get
ltotal
value from leave
table, and then count all of ltotal
. 我想从
leave
表中获取ltotal
值,然后计算所有ltotal
。 Here are my query and code I use: 这是我使用的查询和代码:
$annual_query = pg_query("select ltotal from leave where lapplicant='adam' and ltype=2");
$annual_result = pg_fetch_array($annual_query);
if (pg_num_rows($annual_query) > 0) {
foreach ($annual_result as $data) {
$total_annual = $total_annual + $data;
}
print($total_annual);
}
There are 3 records in the table leave where lapplicant='adam'
and ltype=2
. 表离开中有3条记录,其中
lapplicant='adam'
和ltype=2
。
Each ltotal
is 1. 每个
ltotal
为1。
When I tried to run print($total_annual)
the result is 2 (it must be 3). 当我尝试运行
print($total_annual)
,结果为2(必须为3)。
Then I tried to print_r($annual_result['ltotal']
), the results is just 1 (it must be 1,1,1). 然后我尝试
print_r($annual_result['ltotal']
),结果仅为1(必须为1,1,1)。
Can anyone help me? 谁能帮我? Thank you.
谢谢。
Tamil pointed out the immediate problem. 泰米尔人指出了眼前的问题。 However - why don't you just do this in SQL?
但是-为什么不只在SQL中这样做呢?
select sum(ltotal)
from leave
where lapplicant='adam' and ltype=2
pg_fetch_array()
returns just one row with numeric and associative keys (same value twice when traversed). pg_fetch_array()
仅返回带有数字键和关联键的行(遍历时,相同值两次)。 You should use pg_fetch_all()
and traverse or use while loop on consecutive rows. 您应该使用
pg_fetch_all()
并遍历或在连续的行上使用while循环。
$total_annual = 0;
$annual_query = pg_query("select ltotal from leave where lapplicant='adam' and ltype=2");
while ($row = pg_fetch_array($annual_query)) {
$total_annual = $total_annual + $row['ltotal'];
}
print($total_annual);
or 要么
$total_annual = 0;
$annual_query = pg_query("select ltotal from leave where lapplicant='adam' and ltype=2");
$annual_result = pg_fetch_all($annual_query);
foreach ($annual_result as $row) {
$total_annual = $total_annual + $row['ltotal'];
}
print($total_annual);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.