我正在尝试使用 while 循环显示属于已登录用户的所有食谱。我注意到假设用户有 4 个食谱,第一个不会显示,导致表格中只出现 3 个食谱。如果用户有3个菜谱,第一个菜谱不会显示,导致只显示2个菜谱,以此类推。
我做了我的研究,发现这是因为第一行将被忽略,因此不会显示。
有没有人可以建议我应该对循环进行什么样的更正来解决这个问题?我的代码涉及在表格中显示,这就是为什么我仍然无法弄清楚尽管看了看应该做什么在已经发布和回答的其他问题上。
非常感谢!
<?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> ";
echo "<a href='deleteconfirmation.php?recipeid=$recipeid'>Delete</a> ";
echo "</tr>";
}
echo "</table>";
}
// 8: close the statement
$stmt->close();
// 9: close $mysqli
$mysqli->close();
?>
最佳答案
正如您所说,当您这样做时:
if($stmt->fetch()==null)
代码获取第一行。如果不存在,则条件触发。否则,它会继续,当您开始“真正地”获取行时,第一行已经被获取。
您可以改为检查返回的行数:
$stmt->store_result();
if ($stmt->num_rows == 0) {
echo "You did not have any recipes yet.<br>";
}
关于php - while ($stmt->fetch()) 不获取所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28383262/