簡體   English   中英

如何保存mysqli_result對象的內容?

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

大家好,我目前正在嘗試調試mysqli封裝類的一些代碼。 我遇到了這里描述的問題,嘗試了一些解決方案,這是最新的迭代,並且(似乎不起作用):

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

如果有人知道某種方式存儲結果的方法,或者使用指針和$ result-> free_result()創建系統; 在某個時候打電話來,將不勝感激。 我有點困惑,時間很短。

提前致謝!

截至目前,我的原始實現似乎在進行編輯,不確定通過測試是否成立。 當前,我有一個自定義的$ this-> query()函數,它調用mysqli-> query並將結果存儲在$ this-> result中,但是在某些情況下,似乎$ this-> result變得未設置。 將繼續測試/調試我所擁有的,並查看是否再次發生。 感謝那些回答:)

編輯2通過相當多的試驗和錯誤,我已經追溯了我回到一個表現奇怪的SQL查詢的問題。 似乎不可能從沒有問題(?)的mysqli :: query()存儲結果對象。

您的示例代碼未獲取行。 您將需要執行此操作,其中一種選擇是作為對象進行獲取

$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

您不必在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'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM