【问题标题】:PHP while statement issuesPHP while 语句问题
【发布时间】:2014-06-21 03:44:52
【问题描述】:

我的 PHP while 语句有问题。它是:

$row = mysqli_fetch_array($result);
$time_in_12_hour_format = date("g:i a", strtotime($row['Time']));
while($row = mysqli_fetch_array($result)){  //Creates a loop to loop through results
    echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['Description'] . "</td><td>" . $row['Date'] . " at " . $time_in_12_hour_format . "</td><td>" . $row['Location'] . "</td>";  //$row['index'] the index here is a field name

是的,我确实意识到我定义了两次 $row,但我不确定如何更改它。如果我从 while 语句中删除 $row = mysqli_fetch_array($result) ,页面将不会加载并返回错误。到目前为止,页面加载但表格是空的,即使我知道在我添加军事时间转换器之前表格中显示了一条记录。任何帮助表示赞赏。

【问题讨论】:

  • 先删除$row = mysqli_fetch_array($result);,然后将$time_in_12_hour_format = date("g:i a", strtotime($row['Time']));添加到循环中。

标签: php mysql sql loops while-loop


【解决方案1】:

试试这个

while ($row = mysqli_fetch_array($result)) {  //Creates a loop to loop through results
    $time_in_12_hour_format = date("g:i a", strtotime($row['Time']));
    echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['Description'] . "</td><td>" . $row['Date'] . " at " . $time_in_12_hour_format . "</td><td>" . $row['Location'] . "</td>";  
}

每次调用mysqli_fetch_array 它都会从表中获取一行,所以既然你说你的表有一条记录,那么一条记录将在第一次mysqli_fetch_array 调用中返回,最终第二次调用mysqli_fetch_array 返回NULL 因为表中没有要获取的记录

【讨论】:

    【解决方案2】:

    尝试将 $time_in_12_hour_format 移动到 while 循环中。

    while($row = mysqli_fetch_array($result)){  //Creates a loop to loop through results
        $time_in_12_hour_format = date("g:i a", strtotime($row['Time']));
        echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['Description'] . "</td><td>" . $row['Date'] . " at " . $time_in_12_hour_format . "</td><td>" . $row['Location'] . "</td>";  //$row['index'] the index here is a field name
    }
    

    这也将解决定义 $row 两次,这首先是导致问题的原因。因为您已经调用了mysqli_fetch_array($result),所以您的 while 循环从第 2 行开始。

    【讨论】:

      【解决方案3】:

      应该为每一行设置$time_in_12_hour_format,对吗?如果是,则尝试将其移动到 while 循环内。您当前的代码只会开始显示第 2 行,而第 1 行将被忽略。修改后的代码应如下所示:

      while($row = mysqli_fetch_array($result)){  //Creates a loop to loop through results
          $time_in_12_hour_format = date("g:i a", strtotime($row['Time']));
          echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['Description'] . "</td><td>" . $row['Date'] . " at " . $time_in_12_hour_format . "</td><td>" . $row['Location'] . "</td>";  //$row['index'] the index here is a field name
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-16
        • 1970-01-01
        • 2011-05-11
        • 2021-04-29
        • 2021-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多