Henrikz
Henrikz

Reputation: 441

PHP while loop never ends

How come my while loop never ends? Can't get it to work, maybe there is something wrong with my class?

function getCategory() {

    require_once('includes/database/config.php');

    $database   = new Database();
    $database   ->sqlQuery("SELECT * FROM news_category");    
    $rows = $database   ->sqlNumRows();

    if($rows > 0) {
        while($row = $database->sqlGetRows()) {
            echo "<li><input type='hidden' value='" . $row->id . "' id='hiddenForm' /><span></span> <img src='gfx/close.png' alt='' title='Slett Kategorien' /></li>";
        }
    } else {
        echo "<hr>";
        echo "<br />";
        echo "<span>Det er ingen kategorier her enda!</span>";
    }

}

class Database {

    private $mysqli;
    private $query;
    private $string;

    public function __construct() {
        $this->mysqli = new mysqli('localhost', 'root', '', 'hltv');
    }

    public function sqlQuery($sql) {
        $this->mysqli->query($sql);
        $this->query = $sql;
    }

    public function sqlNumRows() {
        $q = $this->mysqli->query($this->query);
        return $q->num_rows;
    }

    public function sqlGetRows() {
        $q = $this->mysqli->query($this->query);
        return $q->fetch_object();
    }

}

Upvotes: 0

Views: 265

Answers (1)

fresskoma
fresskoma

Reputation: 25781

Because you are always re-querying. Everytime you call #sqlGetRows, you execute the query again, and therefore you always get the first row from the query whenever you call it.

What you could do is, for example:

public function sqlQuery($sql) {
    $this->lastQuery = $this->mysqli->query($sql);
}

public function sqlGetRow() {
    $this->lastQuery->fetch_object();
}

Upvotes: 2

Related Questions