我试图使用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>";
}
(编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|