我正在嘗試使用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();
?>
如果不使用'mysqli_stmt :: store_result()',是否返回正確數量的行? – Sumurai8 2015-02-07 14:33:49
@ Sumurai8:不,看不到[mysqli_result :: $ num_rows]文檔(http://php.net/manual/en/mysqli-result.num-rows.php)。 – Progman 2015-02-07 14:38:58
嗨,我已經取代如果($ stmt-> fetch()== null){ \t回聲「您還沒有任何食譜
」; \t}與Joel Hinz建議的代碼。但是這次網頁顯示一條消息,告訴我用戶在他實際上有4個食譜時沒有任何食譜。 – Dominic 2015-02-07 14:44:20