我遇到以下代码中的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
}
record
中的0条记录相关联,则第一个if
仅按预期显示新记录按钮。record
中的2个或多个记录相关联,for
循环将按预期执行,并按预期显示新记录按钮后面的记录。for
循环不会执行,并显示附加记录按钮。 echo $records->num_rows
将显示我在phpmyadmin中看到的相应记录数。
当$records->num_rows
返回1时,为什么for循环没有按预期执行的任何想法?
答案 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.