duanjianshen4871 2017-09-25 09:58 采纳率: 100%
浏览 19
已采纳

无法通过两种不同的方法循环结果集

I have ran in to a pickle with using a while loop to iterate over a result set.

I execute a query, and pass into a class, storing it as a private variable.

Then I use two separate methods to do a while loop over the result set.

The first method works, the second doesn't.

Here's some code to show example.

<?php

class DataFlow {

    private $resultSet;

    function __construct($results) {
        $this->resultSet = $results;
    }

    function method1() {
        while ($rows = CDB::GetAssoc($this->resultSet)) {
            // works here
            echo $rows;
        }
    }

    function method2() {
        while ($rows = CDB::GetAssoc($this->resultSet)) {
            // doesn't work here 
            echo $rows;
        }
    }

}

$sqlQuery = "....";
$results = CDB::ExecuteQuery($sql);
$dataFlow = new DataFlow($results);

echo $dataflow->method1(); // Works
echo $dataflow->method2(); // Doesn't work.
?>

Now if I edit this to include the query execution locally.. it works

<?php

class DataFlow {

    private $resultSet;

    function __construct($results) {
        $this->resultSet = $results;
    }

    function method1() {
        while ($rows = CDB::GetAssoc($this->resultSet)) {
            // works here
            echo $rows;
        }
    }

    function method2() {
        $sqlQuery = "....";
        $results = CDB::ExecuteQuery($sql);

        while ($rows = CDB::GetAssoc($results)) {
            // now works here 
            echo $rows;
        }
    }

}

$sqlQuery = "....";
$results = CDB::ExecuteQuery($sql);
$dataFlow = new DataFlow($results);

echo $dataflow->method1(); // Works
echo $dataflow->method2(); // Works
?>

I can't seem to figure out why I can't use a result set twice in the same class. Any ideas?

  • 写回答

2条回答 默认 最新

  • doujiao2000 2017-09-25 10:05
    关注

    reading results from a database query involves iterating over some kind of a cursor going through the result rows. Depending on your database class, you might be able to reset this cursor to loop over the results several times if needed. If not, then you would have to perform the query again.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CSS实现渐隐虚线边框
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题