2009-12-05 81 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>";