php - MYSQL 缺少第一行数据

标签 php mysql mysqli fetch associative-array

我编写了一个 PHP 脚本,其中返回餐厅名称、地址、电话号码、营业时间表和自定义菜单的链接。但是,即使数据库中有周一的条目,当我在 mysqli_fetch_assoc 中执行 while 循环时,它也不会显示。这是我的代码:

<?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>';
   ?>

还提供了我在网站上看到的内容。有谁知道为什么会发生这种情况?

  • 我的数据库的小时表屏幕截图 Hours table screenshot from my db

  • 正在打印餐厅营业时间的数据库条目 db entries for restaurant hours being printed

  • 通过 php 打印的小时表示例 2 hours table being printed through php example 2

最佳答案

从代码中删除第 21 行:

$row=mysqli_fetch_assoc($result2);

while循环获取其余记录之前获取第一行。

为什么?

while 循环之外,您调用了第一行并且没有打印它。输出中缺少此行。

关于php - MYSQL 缺少第一行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49677808/

相关文章:

MySql workbench CHECK 约束

php - Mysql 获取不工作

php - mysql中将两个查询合并为单个查询(一个查询的结果输入到另一个查询的表名)

php - mysqli_fetch_assoc()需要参数/调用成员函数bind_param()错误。如何获取并修复实际的mysql错误?

php - 让 PHP 读取我的 postgres select 语句?

php - MYSQL SUM 查询与 Group By 和 Join 问题

mysql - 我在 phpmyadmin 中的输入参数的 MYSQL 存储过程中遇到错误?

c# - 使用 MySql 中的 2 个不同的表登录,它们有自己不同的窗口表单

php - MySQL查询: get the last row of related table on multi table selection

php - 代码优化-mysql输出