2014-10-09 74 views
-2

這是我做SQL的第三天,我相信它確實很小。mysqli_fetch_row只適用於第一行

我有這段代碼。 $ con是我的SQL連接變量。

for ($i = 0; $i < mysqli_num_rows(mysqli_query($con, "SELECT * FROM offers WHERE active='y'")); $i++) 
{ 
    echo '<div class="dottedBox">User: '.mysqli_fetch_row(mysqli_query($con, "SELECT poster FROM offers WHERE active='y'"))[$i]."<br> 
    Has: ".mysqli_fetch_row(mysqli_query($con, "SELECT haveamt FROM offers WHERE active='y'"))[$i]." ".mysqli_fetch_row(mysqli_query($con, "SELECT have FROM offers WHERE active='y'"))[$i].'<br> 
    Wants: '.mysqli_fetch_row(mysqli_query($con, "SELECT wantamt FROM offers WHERE active='y'"))[$i].' '.mysqli_fetch_row(mysqli_query($con, "SELECT want FROM offers WHERE active='y'"))[$i].'</div><br>'; 
} 

第一項輸出正常。然而,每個後續項目將導致以下錯誤:

Notice: Undefined offset: 1 in /var/www/civ/index.php on line 6 

Notice: Undefined offset: 1 in /var/www/civ/index.php on line 7 

Notice: Undefined offset: 1 in /var/www/civ/index.php on line 7 

Notice: Undefined offset: 1 in /var/www/civ/index.php on line 8 

Notice: Undefined offset: 1 in /var/www/civ/index.php on line 8 

運行SELECT * FROM offers;回報這在MySQL(我使用Debian):

mysql> SELECT * FROM offers; 
+----------+-----------+---------+-----------+---------+---------+--------+ 
| poster | have  | haveamt | want  | wantamt | offerid | active | 
+----------+-----------+---------+-----------+---------+---------+--------+ 
| minicl55 | gfdsafdsa |  3 | fdsafdsa |  2 |  1 | y  | 
| minicl55 | jklgdsa |  324 | jfklsdjkl | 4522 |  2 | y  | 
+----------+-----------+---------+-----------+---------+---------+--------+ 

我有兩個問題:

  • 爲什麼不正確輸出
  • 我該如何解決這個問題?
+0

您的代碼正在重新運行每個for循環中的SQL查詢。看來你甚至試圖用新的查詢單獨獲取每一列 - 而不是僅僅獲取一個數組。 – mario 2014-10-09 23:29:14

回答

2

您正在查詢循環中每個值的數據庫。您只需要查詢一次數據庫,然後循環顯示結果。

$result = mysqli_query($con, "SELECT * FROM offers WHERE active='y'"); 

while ($row = mysqli_fetch_assoc($result)) 
{ 
    echo '<div class="dottedBox">User: '.$row['poster']."<br> 
    Has: ".$row['haveamt']." ".$row['offers'].'<br> 
    Wants: '.$row['wantamt'].' '.$row['offers'].'</div><br>'; 
} 
+0

是的,修復它,謝謝。順便說一句,你有一個額外的{第三(或第四取決於你如何編寫代碼)。我無法編輯它,因爲它少於7個字符 – Frank 2014-10-09 23:32:38

+0

哎呀,謝謝你的發現。我修好了它。 – slapyo 2014-10-09 23:34:32

相關問題