当num_rows返回1时,循环不执行

时间:2015-02-01 21:06:58

标签: php mysql for-loop mysqli mysql-num-rows

我遇到以下代码中的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循环将按预期执行,并按预期显示新记录按钮后面的记录。
  • 如果userID与1条记录相关联,则for循环不会执行,并显示附加记录按钮。

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

$records->num_rows返回1时,为什么for循环没有按预期执行的任何想法?

1 个答案:

答案 0 :(得分:0)

when $records->num_rows returns 1 
then 
loop will execute for one time that is $i = 0
when $records->num_rows returns 2
then 
loop will execute for two times that is $i = 0 , $i=1
and  $i === 1 will return true and second record button will be displayed along with first records.
when $records->num_rows returns more than 2
then 
loop will execute for more than two times that is $i = 0 , $i=1 ,$i =2 ..so on
,$i===0 , $i === 1 both will return true as well as else part 
and all button will be displayed.
...
..
so.
when $records->num_rows returns 1
secod records button will not displayed.