coder_1432 coder_1432 - 1 year ago 84
PHP Question

PHP OOP Class query

Good evening, I'm new to OOP and I'm trying to get some results with MYSQLI fetch assoc but I have an issue: only one result is returned in an infinite loop. Please see the code below and let me know what the issue can be:

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 DESC";
return $this->mysqli->query($querystr);


$db= new Database("localhost","root","","news");

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

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

This line causes your function to be executed and to return fresh results over and over. Thus you end up in an infinite loop, always fetching the first result.

The fix:

$result = $db->GetNewsArticles();

while($row = $result->fetch_assoc()){ 
    echo $row["Id"];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download