如何保存mysqli_result对象的内容?

时间:2012-05-31 19:11:54

标签: php mysqli

嘿伙计们我正在尝试为mysqli封装类调试一些代码。我遇到了一个问题here尝试了一些解决方案,这是最新的迭代,并且(似乎不起作用):

$this->result = new stdClass();
foreach($res = $this->conn->query($sql) as $key => $value) {
    $this->result->$key = $value;
}

如果有人知道某种方式以某种方式存储结果或创建一个带有指针和$ result-> free_result()的系统;在某个时候带来召唤它会非常感激。我有点难过,时间很短。

提前致谢!

编辑现在我的原始实现似乎不确定这是否适用于测试。目前我有一个自定义的$ this-> query()函数调用mysqli->查询并将结果存储在$ this->结果中,但是在某些情况下似乎$ this->结果变得未设置。要继续测试/调试我所拥有的内容并查看它是否再次发生。感谢那些回答:)

编辑2通过相当多的试验和错误,我已经追踪了我回到SQL查询表现奇怪的问题。似乎无法在没有问题(?)的情况下从mysqli :: query()存储结果对象。

2 个答案:

答案 0 :(得分:1)

您的示例编码不是获取行。您需要这样做,其中一个选项是fetch as objects

$this->rows = array();

$res = $this->conn->query($sql);

while ($obj = $res->fetch_object()) {
    $this->rows[] = $obj;
}

echo $this->rows[0]->id; // assuming you have a column named id

答案 1 :(得分:0)

您不必在PHP类中提前声明属性。只需动态分配:

foreach($res = $this->conn->query($sql) as $key => $value) {
    $this->result->$key = $value;
}

这将创建一个与$ key值相同的属性。请记住,如果$ key在名称中有空格,您将无法以通常的方式访问该属性。例如:

$key = 'Hello World';
$this->result->$key = 'Hi!';
// now this won't work even though Hello World is the property name:
echo $this->result->Hello World;
// instead do:
echo $this->result->$key;
// or access it like an associative array
echo $this->result['Hello World'];
相关问题