2009-12-05 79 views
10

可以嗎?如何在php/mysql中獲得列名和結果集?

$i = 0; 
while ($row = mysql_fetch_array($result)) 
{ 
    $resultset[] = $row; 
    $columns[] = mysql_fetch_field($result, $i); 
} 

然後嘗試打印

<tr><th><?php echo $columns[0] ?></th><th><?php echo $columns[1] ?></th></tr> 

我得到一個錯誤

Catchable fatal error: Object of class stdClass could not be converted to string 
+0

我注意到,$我不遞增,總是有值0。此外,'$ row'和'$ resultset'在這個例子中未使用,並且'$ result'沒有在示例範圍內定義。 – 2009-12-05 19:10:15

+0

你是對的忘了增加$我:) – programmernovice 2009-12-05 19:24:51

回答

19

嘗試mysql_fetch_field功能。

例如:

<?php 
$dbLink = mysql_connect('localhost', 'usr', 'pwd'); 
mysql_select_db('test', $dbLink); 

$sql = "SELECT * FROM cartable"; 
$result = mysql_query($sql) or die(mysql_error()); 

// Print the column names as the headers of a table 
echo "<table><tr>"; 
for($i = 0; $i < mysql_num_fields($result); $i++) { 
    $field_info = mysql_fetch_field($result, $i); 
    echo "<th>{$field_info->name}</th>"; 
} 

// Print the data 
while($row = mysql_fetch_row($result)) { 
    echo "<tr>"; 
    foreach($row as $_column) { 
     echo "<td>{$_column}</td>"; 
    } 
    echo "</tr>"; 
} 

echo "</table>"; 
?> 
+0

@Atli:漂亮的圖片! :) – 2009-12-05 19:06:41

+0

謝謝。回到'亞! :) – Atli 2009-12-05 19:15:32

8

你想看看

mysql_fetch_assoc 

其中給出的每一行作爲關聯鍵時=>鍵值所在的值對列名稱。

文檔here

12

使用mysql_fetch_assoc只得到一個關聯數組,並檢索與第一次迭代中的列名:

$columns = array(); 
$resultset = array(); 
while ($row = mysql_fetch_assoc($result)) { 
    if (empty($columns)) { 
     $columns = array_keys($row); 
    } 
    $resultset[] = $row; 
} 

現在,您可以用打印表頭第一次迭代:

echo '<table>'; 
$columns = array(); 
$resultset = array(); 
while ($row = mysql_fetch_assoc($result)) { 
    if (empty($columns)) { 
     $columns = array_keys($row); 
     echo '<tr><th>'.implode('</th><th>', $columns).'</th></tr>'; 
    } 
    $resultset[] = $row; 
    echo '<tr><td>'.implode('</td><td>', $rows).'</td></tr>'; 
} 
echo '</table>'; 
+0

你也可以刪除if和do $ columns = isset($ resultset [0])? array_keys($ resultset [0]):array();在循環之外:) – 2009-12-05 19:11:32

+0

嗨,非常好的主意,比使用mysql_fetch_field字段更好,但我投了下面的帖子,因爲它直接回答了我的問題:) – programmernovice 2009-12-05 19:26:35

0

儘管它已被棄用並且不再在PHP 7中使用函數mysql_field_name來避免使用對象,而是返回一個字符串。

0

試試這個

 $result=mysql_query('SELECT * FROM `table1` where id=5') or die ('query failed'); 
echo "<table>"; 
     while ($row=mysql_fetch_assoc($result)) { 
       $column = array_keys($row); 
       for($i=0; $i<sizeof($column); $i++){ 
       echo "<tr><th>".$column[$i]."</th><td>".$row[$column[$i]]."</td></tr>"; 
       } 
      } 
echo "</table>"; 

OR

$result=mysql_query('SELECT * FROM `table1` where id=5') or die ('query failed'); 
    echo "<table>"; 
      $row=mysql_fetch_assoc($result); 
        $column = array_keys($row); 
        for($i=0; $i<sizeof($column); $i++){ 
        echo "<tr><th>".$column[$i]."</th><td>".$row[$column[$i]]."</td></tr>"; 
        } 

    echo "</table>";