Search code examples
phpmysqlmysqlifetchassociative-array

Missing first row of data from MYSQL


I wrote a php script where I return restaurant name, address, phone number, table of store hours and a link to custom menu. However, even if in the database there is an entry for Monday hours it is not showing up when I do a while loop in the mysqli_fetch_assoc. Here is my code:

<?php
session_start();
$con=mysqli_connect("root","");
$rest_id2=$_GET['id'];
$rest_id=(int)$rest_id2;
var_dump($rest_id);
$sql="SELECT * FROM restaurant WHERE restaurant_id='".$rest_id."'";
$result=mysqli_query($con,$sql);
$rows=mysqli_fetch_assoc($result);
echo '<strong>'. "Restaurant name:". '</strong><br><br>';
echo $rows['restaurant_name'];
echo "<br><br>";
echo "<strong>Address: </strong><br><br>";
echo $rows['address_1']." ".$rows['address_2']." ". $rows['city']. ", ". 
$rows['state']. " ". $rows['zip']. "<br><br>";
echo '<strong>'. "Phone number:". '</strong><br><br>';
echo $rows['phone_number']. "<br><br>";
//hours table
$sql2="SELECT * from hours WHERE restaurant_id='".$rest_id."'";
$result2=mysqli_query($con,$sql2);
$row=mysqli_fetch_assoc($result2);
echo "<table border='1' cellpadding='10'><tr><th>Open or Closed</th> . 
<th>Day</th><th>Start Time</th><th>End Time</th></tr>";
$num_rows=mysqli_num_rows($result2);
// var_dump($num_rows);
while($row=mysqli_fetch_assoc($result2)){
    // var_dump($rows);
    if ($num_rows==0){
        echo "No hours data available";
    }
    elseif($row['day']=="Closed"){
        echo "<td><strong>". $row['day']. "</td></strong><br>";
        echo "<td><strong>". $row['open_closed']. "</td></strong><br>";
        echo "<td><strong>". "-". "</td></strong><br>";
        echo "<td><strong>". "-". "</td></tr></strong><br>";
    }
    else{
        echo "<tr><td><strong>". $row['day']. "</td></strong><br>";
        echo "<td><strong>". $row['open_closed']. "</td></strong><br>";
        echo "<td><strong>". $row['start_time']. "</td></strong><br>";
        echo "<td><strong>". $row['end_time']. "</td></tr></strong><br>";
    }
  }
   echo '<a href="' . "custom_menu.php?id=" .$rows['restaurant_id']. '"'. 
   '>'."<strong>Menu specialized for you</strong>" . '<br>'. '</a>';
   ?>

Have also provided what I am seeing in the website. Does anyone know why this is happening?

  • Hours table screenshot from my db Hours table screenshot from my db

  • db entries for restaurant hours being printed db entries for restaurant hours being printed

  • hours table being printed through php example 2 hours table being printed through php example 2


Solution

  • Remove line 21 from your code:

    $row=mysqli_fetch_assoc($result2);
    

    It fetches the first row before the while loop fetches the rest of the records.

    Why?

    Outside of the while loop you call 1st row and did not print it. This row is missing in output.