[英]How to output multiple rows from an SQL query using the mysqli object
假設mysqli對象已經使用全局變量$ mysql實例化(並連接),這是我要使用的代碼。
class Listing {
private $mysql;
function getListingInfo($l_id = "", $category = "", $subcategory = "", $username = "", $status = "active") {
$condition = "`status` = '$status'";
if (!empty($l_id)) $condition .= "AND `L_ID` = '$l_id'";
if (!empty($category)) $condition .= "AND `category` = '$category'";
if (!empty($subcategory)) $condition .= "AND `subcategory` = '$subcategory'";
if (!empty($username)) $condition .= "AND `username` = '$username'";
$result = $this->mysql->query("SELECT * FROM listing WHERE $condition") or die('Error fetching values');
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
return $info;
}
}
在數據庫中有數百個列表,當我調用$ result-> fetch_array()時,它將數組中的第一行放置在數組中。 但是,當我嘗試調用該對象時,似乎只能訪問第一行。 例如:$ listing_row =新列表; while($ listing = $ listing_row-> getListingInfo()){echo $ listing [0]; }
這將輸出數據庫中同一行的無限循環。 為什么不前進到下一行? 如果我移動代碼:
$this->listing = $result->fetch_array() or die('could not create object');
foreach ($this->listing as $key => $value) :
$info[$key] = stripslashes(html_entity_decode($value));
endforeach;
如果將其移出類,它將在按while語句循環時一次輸出一行,這與預期的完全一樣。 有沒有一種方法可以編寫此代碼,以便我可以將fetch_array()調用保留在類中,並且仍然可以遍歷記錄?
您的對象從根本上來說是有缺陷的-每次您調用getListingInfo()方法時,它都會重新運行查詢。 同樣, mysql_fetch_array()
不會獲取整個結果集,而只會獲取下一行,因此您的方法可以歸結為:
對對象的每次調用都會創建一個新查詢,一個新結果集,因此將永遠無法獲取第二,第三等行。
除非您的數據集“巨大”(即:比您想要/可以設置的PHP memory_limit大),否則沒有理由不獲取整個集合並一次性處理所有數據,如上面的Jacob回答所示。
附帶說明,使用反斜杠使我想知道您的PHP安裝是否啟用了magic_quotes_gpc。 長期以來,此功能已被棄用,每當v6.0出現時,它將從PHP中刪除。 如果您的代碼按這種安裝方式運行,則可能會浪費合法的轉義數據。 同樣,將編碼/轉義的數據存儲在數據庫中通常不是一個好主意。 數據庫應包含數據的“原始”副本,然后在需要處理版本時根據需要對其進行處理(轉義,引用等)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.