phptimeslots

PHP while loop times


This is my first time try to use object oriented programming. I'm trying to repeat the timeslot from the database but I'm only getting one result.

timeslot table contains:

10:00:00  
10:15:00
10:30:00

in PHP class:

 class booking {
     function __construct($mysqli) { 

     }

     function get_timeslot() {
         global $mysqli;

         $q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");

         while($r = $q->fetch_array(MYSQLI_ASSOC)) :
             return $r['times'];
         endwhile;

         $mysqli->close();
     }
 }

in the webpage to showing the looping times:

 $booking = new booking($mysqli);

 <?php echo $booking->get_timeslot(); ?>

result:

10:00:00

Solution

  • return is returning the value for your function, thus you'll only receive 1 value returned. Try

    echo $r['times'].'<br/>';
    

    or

     function get_timeslot(){
         global $mysqli;
    
         $q = $mysqli->query("SELECT id_timeslot, times FROM timeslot");
         $timeSlots = array();
    
         while($r = $q->fetch_array(MYSQLI_ASSOC))
         {
             $timeSlots[] = $r['times'];
         }
    
         $mysqli->close(); 
         return $timeSlots;
     }