2014-10-29 54 views
0

請幫助我,我是一個初學者。我需要從我的數據庫中顯示多個字段。但不知何故,這個代碼只顯示第一行。錯誤顯示多個字段

if(mysql_num_rows($result)>0) 
{ 
$output .= "<p>Table: $tbl</p><p>"; 
// BUG - SHOULD LOOP THRU MULTIPLE rows 
$row = mysql_fetch_row($result); 
$i = 0; 
while ($i < mysql_num_fields($result)) 
{ 
    //echo "Information for column $i:<br />\n"; 
    $fieldN = mysql_field_name($result, $i); 
    if (!$fieldN) { $output .= "No info available<br />\n"; } 
    if ($row[$i]) { 
     $fieldN = mysql_field_name($result, $i); 
     if (!$fieldN) { $fieldN = "No_field_name"; } 
     $output .= " $tbl F: $fieldN V: $row[$i]<br />\n"; 
    } 
    $i++; 
} // end while 
    $output .= "</p>"; 
} // end if number of rows > 0 

回答

0

在你的代碼是獲取與$row = mysql_fetch_row($result);結果從一個記錄作爲一個數字數組返回只有一行。

中序獲得ResultSet中的所有記錄,你必須使用$row = mysql_fetch_row($result);

嘗試用代碼來從結果集的每個記錄:

while ($row = mysql_fetch_row($result)) // while there are results 
{ 
    // get each field values inside this loop 
} 
+0

我正在使用選項/下拉表單來選擇我想要顯示的表,每個表中的字段值是不同的。 – Beginner 2014-10-29 07:20:28

0

您可以嘗試使用

while ($row = mysqli_fetch_array($result)) { 

而不是

while ($i < mysql_num_fields($result)) 

mysqli_fetch_array()允許您將數據作爲數字數組和作爲關聯數組提取。

如果你有一個數據庫字段名爲ID是數據庫表的第一行上,你可以使用這樣的事情:

$id = $row[0]; 
$id = $row['ID']; 

相比fetch_row和FETCH_ASSOC只能在獲取他們可以(分別爲數字數組和關聯數組)。

+0

其實我使用選項/下拉表單來選擇我想要顯示的表格,每個表格中的字段值是不同的。 – Beginner 2014-10-29 07:21:29

+0

是的。這可以用這個來完成。您所要做的就是根據您正在比較的值查詢數據庫並運行while循環。它所做的是循環遍歷數據庫中的每一行,以滿足您的需求(在這種情況下,該表的名稱)。 – FortMauris 2014-10-29 07:26:04

0
// LOOP THRU MULTIPLE rows 
while ($row = mysql_fetch_row($result)) { 
    $i = 0; 
    while ($i < mysql_num_fields($result)) { 
     //echo "Information for column $i:<br />\n"; 
     if ($row[$i]) { 
      $fieldN = mysql_field_name($result, $i); 
      if (!$fieldN) { $fieldN = "No_field_name"; } 
      $output .= " $tbl F: $fieldN V: $row[$i]<br />\n"; 
     } 
     $i++; 
    } // end while loop thru fields in each row 
    $output .= "</p>"; 
    } // end while there is a row