I'm experiencing an issue with a for loop in the following code:
<?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
}
- If the userID is associated with 0 records in the table
record
, the firstif
displays the new record button only, as expected. - If the userID is associated with 2 or more records in the table
record
, thefor
loop executes as expected, displaying the records followed by the new record button, as expected. - If the userID is associated with 1 record, the
for
loop does not execute, and the additional record button is displayed.
echo $records->num_rows
will display the corresponding number of records I see in phpmyadmin.
Any ideas why the for loop is not executing as expected when $records->num_rows
returns 1?