对于每个/查询,都没有给出正确的值

时间:2014-06-26 03:10:16

标签: php mysql sql postgresql

我的数据库中有一张表。我想从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)。

任何人都可以帮助我吗?谢谢。

2 个答案:

答案 0 :(得分:2)

泰米尔人指出了眼前的问题。但是 - 为什么不在SQL中执行此操作?

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);