【问题标题】:PHP OOP Class queryPHP OOP 类查询
【发布时间】:2016-07-24 02:10:50
【问题描述】:

晚上好,我是 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"];
}

【问题讨论】:

    标签: php class oop mysqli


    【解决方案1】:
    while($row = $db->GetNewsArticles()->fetch_assoc())
    

    这一行会导致你的函数被执行并一遍又一遍地返回新的结果。因此,您最终会陷入无限循环,始终获取第一个结果。

    修复:

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

    【讨论】:

    • @coder_1432 不客气。一定要对好的答案投赞成票并选择其中一个。编码愉快。
    【解决方案2】:

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

    $db= new Database("localhost","root","","news");
    $results = $db->GetNewsArticles();
    
    while($row = $results->fetch_assoc()){ 
        echo $row["Id"];
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 2015-08-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多