我有一个 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 按值传递到构造函数中, 无法弄清楚为什么会发生这种情况,任何建议表示赞赏!
最佳答案
在构造函数中完成 $result->fetch_assoc()
后,结果集中的指针现在位于末尾,因此任何进一步的调用都将返回 NULL
。相反,您应该迭代您的 result_array
:
<?php foreach($obj->result_array as $row): ?>
....
<?php endforeach; ?>
此外,$result
不是按值传递的,它是对同一对象的引用,而不是克隆。
关于再次执行 fetch_assoc() 后的 php mysql 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22989730/