我的数据库里有一张表。我想从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)。
有人能帮我吗?谢谢您。

最佳答案

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

关于php - 对于每个/查询未给出正确的值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24421767/

10-11 01:54