I’m having issues to display all the rows inside my database table. But only one rows display instead of all data.
$query= mysqli_query($conn,"select* from food_table");
if (mysqli_num_rows($query)>0){
echo "<p style='color: green;'>See Below the Available Foods<br></p>";
while($row=mysqli_fetch_assoc($query)){
$food_name= $row['food_name'];
$food_info = $row['food_info'];
$food_price = $row['food_price'];
$vendor_id = $row['vendor_id'];
$default_miles = $row['default_miles'];
$food_date= $row['date'];
}
$foods= array($food_name,$food_info,$food_price,$vendor_id,$default_miles, $food_date );
foreach($foods as $foodss){
echo "$foodss.<br/>";
}
please see result below;enter image description here
3
Answers
You’ve got your loops wrong. You first loop through all rows in the database and assign them to the variables
$food_name
etc, however, only after you exit the while loop you create an array with those variables. This doesn’t work, as now the$food_name
etc just has the value of the last row.What you’d want is something like this:
Now you put the food name for every row on the page.
Always keep in mind what your loop is actually doing. Every iteration of the while loop you set the variables
$food_name
to a certain value. Print the value in the current iteration to get all values on the page. If you want to store those values in an array, you would have to do something like$food_names[] = $row['food_name']
.You have to store all data inside a array before display or you can print it inside while loop. best practice is store data inside array first.
try this: ($foods array goes within while loop to store all data)
//foreach code as it is