Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Fetch data twice

My function looks like that.

 private function generateTree($courseID) {
        $q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?";
        $stmt = $this->db->prepare($q);
        $stmt->bind_param("i", $courseID);
        $stmt->execute();
        $stmt->store_result();
        if ($stmt->num_rows > 0) {
            $stmt->bind_result($id, $lName, $cName);
            echo "<li> <a href='#'>$cName</a> <ul>";
            while ($stmt->fetch()) <====HERE!!!
                echo "<li> <a href='?course=$courseID&lesson=$id'> $lName </a></li>";
            echo "</ul> </li>";
        }
    }

The problem is that I'm starting to fetch data inside a while condition, but I need it before the while, too. Can I fetch data twice? Any other suggestions?

like image 848
heron Avatar asked Aug 09 '26 19:08

heron


1 Answers

It's been four years, but in case someone stumble upon this question like I did:

while ($stmt->fetch()) {
  // do your thing
}

$stmt->data_seek(0);

while ($stmt->fetch()) {
  // do something other
}

You can read documentation here

like image 73
Cheslab Avatar answered Aug 12 '26 12:08

Cheslab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!