for 循环在 num_rows 返回 1 时未执行



我在以下代码中遇到了 for 循环的问题:

<?php
// connect to database and establish $link, okay
// log in user if possible and get $userID, okay
// if logged in, get list of records
$sql = "SELECT id,name FROM `record` WHERE user=$userID ORDER BY accessed";
$records = $link->query($sql); // returns rows successfully
if (!($records->num_rows > 0)) { // if query returns no rows
  // display button to create a record
} else {
  // if query returns rows
  for ($i = 0; $i < $records->num_rows; $i++) {
    $row = $records->fetch_assoc();
    if ($i === 0) {
      // display first existing record button which is also a css hover to display subsequent buttons
    } else if ($i === 1) {
      // display second existing record button if exists
    } else {
      // display all other existing record buttons
    }
  }
  // display button to create an additional record
}
  • 如果 userID 与表 record 中的 0 条记录相关联,那么第一个if仅显示新记录按钮,如预期的那样。
  • 如果 userID 与表 record 中的 2 条或更多记录相关联,则 for 循环将按预期执行,并按预期显示记录后跟新记录按钮。
  • 如果用户 ID 与 1 条记录关联,则不会执行for循环,并显示附加记录按钮。

echo $records->num_rows将显示我在phpmyadmin中看到的相应数量的记录。

知道为什么 for 循环在返回 1 时没有按预期执行$records->num_rows吗?

当 $records->num_rows 返回 1 时然后循环将执行一次,即 $i = 0当 $records->num_rows 返回 2 时然后循环将执行两次,即 $i = 0 , $i=1$i === 1 将返回 true,第二个记录按钮将与第一个记录一起显示。当 $records->num_rows 返回超过 2 时然后循环将执行两次以上,即 $i = 0 ,$i=1 ,$i =2 .。等等,$i===0 , $i === 1 两者都将返回 true 以及 else 部分将显示所有按钮。.....所以。当 $records->num_rows 返回 1 时SECOD 记录按钮将不会显示。

最新更新