晚上好,我是OOP的新手,我正试图用MYSQLI获取assoc获得一些结果,但我遇到了一个问题:在无限循环中只返回一个结果。请查看下面的代码,让我知道问题可能是什么:
class Database{
private $host;
private $user;
private $password;
private $db;
private $mysqli;
function __construct($host,$user,$pass,$data) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->data = $data;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->data);
}
public function GetNewsArticles(){
$querystr="SELECT newsarticle.Id, newsarticle.Title from newsarticle GROUP BY newsarticle.Id ORDER BY newsarticle.id DESC";
return $this->mysqli->query($querystr);
}
}
$db= new Database("localhost","root","","news");
$db->GetNewsArticles();
while($row = $db->GetNewsArticles()->fetch_assoc()){
echo $row["Id"];
}
while($row = $db->GetNewsArticles()->fetch_assoc())
这一行使您的函数被执行,并反复返回新的结果。因此,您最终会进入一个无限循环,总是获取第一个结果。
修复:
$result = $db->GetNewsArticles();
while($row = $result->fetch_assoc()){
echo $row["Id"];
}
您需要在从GetNewsArticles()
返回的变量中捕获mysqli_result对象,并在上调用fetch_assoc()
,:
$db= new Database("localhost","root","","news");
$results = $db->GetNewsArticles();
while($row = $results->fetch_assoc()){
echo $row["Id"];
}