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

pro*_*ice 12 php mysql

这个可以吗 ?

$i = 0;
while ($row = mysql_fetch_array($result))
{
    $resultset[] = $row;
    $columns[] = mysql_fetch_field($result, $i);
}
Run Code Online (Sandbox Code Playgroud)

然后在尝试打印时

<tr><th><?php echo $columns[0] ?></th><th><?php echo $columns[1] ?></th></tr>
Run Code Online (Sandbox Code Playgroud)

我收到了一个错误

Catchable fatal error: Object of class stdClass could not be converted to string
Run Code Online (Sandbox Code Playgroud)

Atl*_*tli 24

试试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>";
?>
Run Code Online (Sandbox Code Playgroud)


Gum*_*mbo 14

用于mysql_fetch_assoc仅获取关联数组并使用第一次迭代检索列名:

$columns = array();
$resultset = array();
while ($row = mysql_fetch_assoc($result)) {
    if (empty($columns)) {
        $columns = array_keys($row);
    }
    $resultset[] = $row;
}
Run Code Online (Sandbox Code Playgroud)

现在您也可以使用第一次迭代打印表头:

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>';
Run Code Online (Sandbox Code Playgroud)


Dou*_* T. 8

你想看看

 mysql_fetch_assoc
Run Code Online (Sandbox Code Playgroud)

这将每行作为关联键=>值对,其中键是列名.

文档在这里