PHP OOP while循环

时间:2015-10-03 07:30:05

标签: php mysql oop

我遇到了使用OOP样式从mysql循环数据的问题。

所以,这是我的代码:

class mysql {

private $host;
private $username;
private $password;
private $database;
public $con;

    public function connect($setHost, $setUsername, $setPassword, $setDatabase) {

        $this->host = $setHost;
        $this->username = $setUsername;
        $this->password = $setPassword;
        $this->database = $setDatabase;

        $this->con = mysqli_connect($setHost, $setUsername, $setPassword, $setDatabase);            
    }

    public function query($setQuery) {

        $query = mysqli_query($this->con, $setQuery);

        return $query;      
    }

    public function fetch($setFetch) {

        $fetch = mysqli_fetch_assoc($this->query($setFetch));

        return $fetch;  
    }
}


$objMysql = new mysql();
$con = $objMysql->connect("localhost" , "root" , "root" , "test");

while ($dataSlideshow = $objMysql->fetch("SELECT * FROM slideshow)) {
<h1><?php echo $dataSlideshow['images']; ?></h1>
}

问题是,当我刷新页面时,它在页面中没有限制,我不知道为什么,但是,在mysql表中,它只包含三个幻灯片?所以,我的电脑挂了,强行关闭浏览器。我的代码在这里出了什么问题?

2 个答案:

答案 0 :(得分:1)

根据您的函数定义,您的代码将是

$rs=$objMysql->query("SELECT * FROM slideshow");
while ($dataSlideshow = $objMysql->fetch($rs)) {
<h1><?php echo $dataSlideshow['images']; ?></h1>
}

并替换此功能定义

 public function fetch($rs) {

        $row = mysqli_fetch_assoc($rs);

        return $row;  
    }

答案 1 :(得分:0)

每次你做

$fetch = mysqli_fetch_assoc($this->query($setFetch));

function $this->query运行并执行查询。所以它永远不会停止。 即使您将$rs传递给fetch函数 - fetch仍会始终为您带来一个结果。

所以,我认为你应该在没有函数fetch的情况下迭代结果:

$objMysql = new mysql();
$con = $objMysql->connect("localhost" , "root" , "root" , "test");

while ($dataSlideshow = mysqli_fetch_assoc($objMysql->query("SELECT * FROM slideshow"))) {
    // do something
}