假设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]; }
这会输出db中同一行的无限循环。为什么它没有前进到下一行? 如果我移动代码:
$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()调用并仍然循环记录?
答案 0 :(得分:0)
您的对象存在根本缺陷 - 每次调用getListingInfo()方法时它都会重新运行查询。同样,mysql_fetch_array()
不会获取整个结果集,它只会获取下一行,因此您的方法归结为:
对对象的每次调用都会创建一个新查询,一个新的结果集,因此永远无法获取第二,第三等......行。
除非你的数据集是“巨大的”(即:大于你想要的/可以设置PHP memory_limit),没有理由不取一整套并一次性处理它,如上面雅各布的回答所示
作为旁注,使用stripslashes让我想知道你的PHP安装是否启用了magic_quotes_gpc。这个功能很久就被弃用了,每当v6.0发布时都会从PHP中删除。如果您的代码在此类安装中按原样运行,则可能会使数据中的合法转义无效。同样,将编码/转义数据存储在数据库中通常是个坏主意。数据库应包含数据的“原始”副本,然后在需要处理版本时根据需要处理它(转义,引用等)。