简体   繁体   English

如何保存mysqli_result对象的内容?

[英]How can I save the contents of a mysqli_result object?

Hey guys Im currently trying to debug some code for a mysqli encapsulation class. 大家好,我目前正在尝试调试mysqli封装类的一些代码。 Ive run into a problem described here have tried a few solutions with this being the latest iteration and (doesn't seem to work): 我遇到了这里描述的问题,尝试了一些解决方案,这是最新的迭代,并且(似乎不起作用):

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

If anyone knows a way to store the results somehow or create a system with pointers and $result->free_result(); 如果有人知道某种方式存储结果的方法,或者使用指针和$ result-> free_result()创建系统; bring called at sometime it would be much appreciated. 在某个时候打电话来,将不胜感激。 Im a little stumped and very short for time. 我有点困惑,时间很短。

Thanks in advance! 提前致谢!

EDIT as of right now my original implementation seems to be working not sure if this will hold true through testing. 截至目前,我的原始实现似乎在进行编辑,不确定通过测试是否成立。 Currently I have a custom $this->query() function calling mysqli->query and storing the results in $this->result, however under some circumstances it seems $this->result becomes unset. 当前,我有一个自定义的$ this-> query()函数,它调用mysqli-> query并将结果存储在$ this-> result中,但是在某些情况下,似乎$ this-> result变得未设置。 Going to keep testing/debugging what I have and see if it happens again. 将继续测试/调试我所拥有的,并查看是否再次发生。 Thanks to those who answered :) 感谢那些回答:)

EDIT 2 Through a fair bit of trial and error Ive traced the issue I was having back to a SQL query behaving oddly. 编辑2通过相当多的试验和错误,我已经追溯了我回到一个表现奇怪的SQL查询的问题。 It seems its not possible to store the resulting object from mysqli::query() without issue(?). 似乎不可能从没有问题(?)的mysqli :: query()存储结果对象。

Your example coding isn't fetching rows. 您的示例代码未获取行。 You'll need to do that and one of the options is to 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

You don't have to declare properties ahead of time in PHP classes. 您不必在PHP类中提前声明属性。 Just assign it dynamically: 只需动态分配即可:

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

That will create a property with the same name as the value of $key. 这将创建一个与$ key的名称相同的属性。 Just keep in mind that if $key has spaces in the name you won't be able to access the property the usual way. 请记住,如果$ key名称中有空格,则将无法以通常的方式访问该属性。 For example: 例如:

$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'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM