PHP循环永远不会结束

时间:2011-03-07 23:30:52

标签: php loops mysqli while-loop

为什么我的while循环永远不会结束?无法让它发挥作用,也许我的班级出了问题?

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();
    }

}

1 个答案:

答案 0 :(得分:2)

因为您总是需要重新查询。每次调用#sqlGetRows时,都会再次执行查询,因此无论何时调用它,都始终从查询中获取第一行。

你可以做的是,例如:

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

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