Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the columns names along with resultset in php/mysql?

Tags:

php

mysql

Is this OK ?

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

Then when trying to print

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

I got an error

Catchable fatal error: Object of class stdClass could not be converted to string
like image 646
programmernovice Avatar asked Dec 05 '09 18:12

programmernovice


People also ask

How do I get columns from ResultSet?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.

How do I get column names in PHP Mysqli?

PHP mysqli fetch_fields() Function.


2 Answers

Try the mysql_fetch_field function.

For example:

<?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>";
?>
like image 151
Atli Avatar answered Oct 11 '22 10:10

Atli


Use mysql_fetch_assoc to get only an associative array and retrieve the column names with the first iteration:

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

Now you can print the head of your table with the first iteration as well:

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>';
like image 26
Gumbo Avatar answered Oct 11 '22 11:10

Gumbo