一尘不染

如何在php / mysql中获取列名和结果集?

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

阅读 436

收藏
2020-05-17

共1个答案

一尘不染

尝试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>";
?>
2020-05-17