1

i had a problem with looping data from mysql using OOP style.

so, here is my code:

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>
}

the problem was, when i refreshing the page, it excutes without limited in the page, i dont know why, but, in mysql table, it contains only three slideshow? so, my computer got hang, and force to close the browsers. what's wrong with my code here?

2 Answers 2

1

By your function definition , your code would be

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

And replace this function definition

 public function fetch($rs) {

        $row = mysqli_fetch_assoc($rs);

        return $row;  
    }
Sign up to request clarification or add additional context in comments.

1 Comment

still not working Mr.Rohit, is it possible that my class has wrong/bad code?
0

Every time you do

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

function $this->query runs and executes a query. So it will never stops. Even if you pass $rs to fetch function - fetch will still brings you one result always.

So, i think you should iterate through results without function fetch:

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

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

1 Comment

this one cause infinite loop, but, i appreciate ur answer. thank you so much Mr. U_minder!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.