2015-02-07 43 views
4

我正在嘗試使用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>&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(); 
?> 

回答

3

正如你所說的,當你這樣做:

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

代碼讀取第一行。如果它不存在,則觸發條件。否則,它會繼續,並且當你開始提取「真實」的行時,第一個已經被提取。

你可以做的,而不是被檢查的行數返回:

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

如果不使用'mysqli_stmt :: store_result()',是否返回正確數量的行? – Sumurai8 2015-02-07 14:33:49

+0

@ Sumurai8:不,看不到[mysqli_result :: $ num_rows]文檔(http://php.net/manual/en/mysqli-result.num-rows.php)。 – Progman 2015-02-07 14:38:58

+0

嗨,我已經取代如果($ stmt-> fetch()== null){ \t回聲「您還沒有任何食譜
」; \t}與Joel Hinz建議的代碼。但是這次網頁顯示一條消息,告訴我用戶在他實際上有4個食譜時沒有任何食譜。 – Dominic 2015-02-07 14:44:20

0

......即使這是一個有點老。問題是,如果存在結果(比較中的一個和while循環的開始處的一個),則獲取2次。因此,第一條記錄被滑行。而不是使用「while」循環,「do while」會避免這種情況,因爲下一次獲取會在循環結束時發生。