PHP OOP类查询

时间:2016-07-24 02:10:51

标签: php class oop mysqli

晚上好,我是OOP的新手,我正在尝试使用MYSQLI fetch 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"];
}

2 个答案:

答案 0 :(得分:1)

您需要捕获从GetNewsArticles()返回的变量中的mysqli_result对象,并在 上调用fetch_assoc()

$db= new Database("localhost","root","","news");
$results = $db->GetNewsArticles();

while($row = $results->fetch_assoc()){ 
    echo $row["Id"];
}

答案 1 :(得分:1)

while($row = $db->GetNewsArticles()->fetch_assoc())

此行会导致您的函数被执行并反复返回新的结果。因此,您最终会进入无限循环,始终获取第一个结果。

修复:

$result = $db->GetNewsArticles();

while($row = $result->fetch_assoc()){ 
    echo $row["Id"];
}