while ($stmt->fetch()) 不获取所有行

while ($stmt->fetch()) not fetching all rows

我正在尝试使用 while 循环显示属于已登录用户的所有食谱。我注意到假设,用户有 4 个食谱,第一个不会显示,导致 table 中只出现 3 个食谱。如果用户有3个菜谱,第一个菜谱不会显示,导致只显示2个菜谱等。

我研究了一下,发现这是因为第一行将被忽略,因此不会显示。

有没有人可以建议我应该对循环进行什么样的更正来解决这个问题?我的代码涉及在 table 中显示,这就是为什么我仍然无法弄清楚是什么尽管已经查看了已经发布和回答的其他问题,但应该完成。

非常感谢!

<?php

// 0: Instead of hard coding I shall declare the value first

$userid = $_SESSION['userid'];

// 1: Connect to forumdb database

$mysqli = new mysqli("localhost", "root", null, "recipedb") or exit("Error connecting to database");

// 2: Prepare the statement to select recipename,recipeid,,imagefile belonging to the $userid from recipe table

$stmt = $mysqli->prepare("Select recipename,recipeid,imagefile from recipe where userid=?");

// 3: Bind the values

$stmt->bind_param("s", $userid);

// 4: Execute the statement

$stmt->execute();

// TODO 5: bind results into $recipename,$recipeid and $imagefile

$stmt->bind_result($recipename, $recipeid, $imagefile);

if ($stmt->fetch() == null) {
    echo "You did not have any recipes yet.<br />";
}
else {
    echo "<table style=width:100% >";
    echo "<tr><td><b>Recipe</b></td><td><b>Actions</b></td></tr>";

    // Use while loop to fetch messages and put in a <table>
    // if

    while ($stmt->fetch()) {
        echo "<tr>";

        // 6: In 1st <td>, display recipename,recipeid,imagefile

        echo "<td><b>$recipename</b><br /><b>Recipe ID:</b>$recipeid<br /> <img src='images/$imagefile'    height='125' width='125'              >   </td>";

        // 7: In 2nd <td>, display View hyperlink
        // The View hyperlink links to recipedetails.php
        // The delete hyperlink links to deleterecipes.php

        echo "<td> <a href='recipedetails.php?recipeid=$recipeid'>View</a>&nbsp";
        echo "<a href='deleteconfirmation.php?recipeid=$recipeid'>Delete</a>&nbsp";
        echo "</tr>";
    }

    echo "</table>";
}

// 8: close the statement

$stmt->close();

// 9: close $mysqli

$mysqli->close();
?>

正如您所说,当您这样做时:

if($stmt->fetch()==null)

代码获取第一行。如果不存在,则条件触发。否则,它会继续,当您开始获取行 "for real" 时,第一行已经被获取。

您可以改为检查返回的行数:

$stmt->store_result();
if ($stmt->num_rows == 0) {
    echo "You did not have any recipes yet.<br>";
}

...即使这个也有点老了。问题是,如果有结果,您会获取 2 次(一次在比较中,一次在 while 循环开始时)。因此跳过第一条记录。 "do while" 没有使用 "while" 循环,而是避免了这种情况,因为下一次提取发生在循环结束时。