再次执行fetch_assoc()之后的php mysql结果

时间:2014-04-10 13:39:47

标签: php mysql

我有一个php类文件,比如将mysql结果存储到数组:

<?php
class myclass{
    public $result_array;

    function __construct($result){
        while($row = $result->fetch_assoc()){
            $this->result_array[] = $row;
        }
    }
}
?>

并在php页面中:

$obj = new myclass($result);

到目前为止工作正常,但后来我尝试再次从$ result中获取数据,如:

<?php while($row = $result->fetch_assoc()): ?>
    <tr>
    <?php foreach ($row as $cell): ?>
        <td><?php echo $cell; ?></td>
    <?php endforeach; ?>
    </tr>
<?php endwhile; ?>

然后fetch_assoc()部分不起作用,因为我将$ result by value传递给构造函数, 无法弄清楚为什么会发生这种情况,任何建议都表示赞赏!

1 个答案:

答案 0 :(得分:1)

在构造函数中完成$result->fetch_assoc()之后,结果集中的指针现在结束,因此任何进一步的调用都将返回NULL。相反,您应该迭代result_array

<?php foreach($obj->result_array as $row): ?>
....
<?php endforeach; ?>

此外,$result未按值传递,它是对同一对象的引用,而不是克隆。

相关问题