我的数据库中有一张表。我想从ltotal
表中获取leave
值,然后计算所有ltotal
。这是我使用的查询和代码:
$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);
}
表格中有3条记录离开lapplicant='adam'
和ltype=2
。
每个ltotal
为1。
当我尝试运行print($total_annual)
时,结果为2(必须为3)。
然后我尝试print_r($annual_result['ltotal']
),结果只有1(必须是1,1,1)。
任何人都可以帮助我吗?谢谢。
答案 0 :(得分:2)
select sum(ltotal)
from leave
where lapplicant='adam' and ltype=2
答案 1 :(得分:2)
pg_fetch_array()
只返回带有数字和关联键的一行(遍历时两次相同的值)。您应该使用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);
或
$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);