简体   繁体   中英

Loop through MySQL results PHP

So, I'd like to make a loop that loops through the results from the following code:

$check_events = "SELECT * FROM events_meedoen WHERE username=:username";
    $stmt_check = $db->prepare($check_events);
    $stmt_check->bindParam(':username', $username);
    $stmt_check->execute();

    $events_row = $stmt_check->fetch(PDO::FETCH_BOTH);
    $event_id = $events_row['event_id'];

    $get_event = "SELECT * FROM agenda WHERE event_id=:event_id";
    $stmt = $db->prepare($get_event);
    $stmt->bindParam(':event_id', $event_id);
    $stmt->execute();

So, for example, I'd like to get all results with the $event_id gotten by checking the agenda for all events that the user is signed up for.

This should result in 2 for my account, which it does not because it only checks once. Any help? :)

you need to put your call to fetch in a while loop. As you can see from the docs , PDO::fetch calls the next record from the result set.

so, something like this will loop through all of the results:

while($events_row = $stmt_check->fetch(PDO::FETCH_BOTH)) {
    $event_id = $events_row['event_id'];
    // do something with the $events_row array here
}

because PDO::fetch returns false when it hits the end of the result set, the while loop knows when to stop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM