【问题标题】:Why is PDOStatement->columnCount not returning the right number?为什么 PDOStatement->columnCount 没有返回正确的数字?
【发布时间】:2011-02-01 16:19:41
【问题描述】:

我首先查询数据库以获取与某个用户 ID 关联的所有记录,然后我需要进入并修改数组,因为其中一个字段是一个 ID,我需要与该 ID 关联的名称。

所以我使用 columnCount 遍历 id 索引处的结果数组,并将其替换为正确的名称,这对于前六个结果来说效果很好。 columnCount 仅返回 6,但前六个已按应有的方式重命名。但除此之外,它会从该 pdostatement 中获取结果并正常填充表,其中包含所有相关数据,现在 17 行。

为什么它返回 6,或者我在做什么来得到错误的列数?

global $__CMS_CONN__;
    $timeqry = 'SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = '.$_SESSION['user_id'];
    $stmt = $__CMS_CONN__->prepare($timeqry);
    $stmt->execute();
    $columns = $stmt->columnCount();
    print $columns;
    if($stmt)
    {
        $arrValues = $stmt->fetchAll(PDO::FETCH_ASSOC);

        for($x=0;$x<$stmt->columnCount();$x++)
        {
            global $__CMS_CONN__;
            $qry = 'SELECT facility FROM facility_db WHERE id = '.$arrValues[$x]['facility_id'];
            $stmt1 = $__CMS_CONN__->prepare($qry);
            $stmt1->execute();
            if($stmt1)
            {
                $facilityName = $stmt1->fetchAll(PDO::FETCH_ASSOC);
                foreach ($facilityName as $item)
                {
                    foreach ($item as $key => $val)
                    {
                        $arrValues[$x]['facility_id'] = $val;
                    }
                }
            }
        }
        print "<table style=\"font-size:90%\">\n";
        print "<tr>\n";
        print "<th style=\"width:100%\">Facility</th>";
        print "<th>Program</th>";
        print "<th>Date</th>";
        print "<th>Visit Length</th>";
        print "<th>Mileage</th>";
        print "<th>Served</th>";
        print "</tr>";
        foreach ($arrValues as $row)
        {
            print "<tr>";
            foreach ($row as $key => $val)
            {
                print "<td>$val</td>";
            }
            print "</tr>\n";
        }
        print "</table>\n";
    }

【问题讨论】:

    标签: php pdo


    【解决方案1】:

    您在第一个 SELECT 查询中要求六列:

    SELECT facility_id, program, date, visit_length, mileage, served FROM timesheet_db WHERE volunteer_id = $_SESSION['user_id']
    

    所以,columnCount() 自然是 6。它不会将列数乘以返回的行数或类似的值。

    如果您想要行数,则需要count($arrValues)(手册上说rowCount() 的数据库行为与SELECTs 不一致)。

    【讨论】:

    • 哈哈!男孩,我觉得自己像个迟到。我正在尝试获取返回的结果数
    • @Ryan:那是rowCount。但是,如果您要遍历行,为什么不只做foreach ($stmt as $row)。 PDO 太棒了,为什么不使用它的棒呢?
    • 是的,我在寻找 rowCount,我想我需要一些咖啡什么的。谢谢你叫醒我。
    • @nikic:我也想到了rowCount(),但手册上说它可能不会计算使用SELECT 选择的行,因此不应依赖。
    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2017-09-13
    • 2015-03-21
    • 1970-01-01
    • 2016-12-30
    相关资源
    最近更新 更多