tags:

views:

221

answers:

3

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
+5  A: 

You want to look at

 mysql_fetch_assoc

Which gives each row as an associative key => value pair where the key is the column name.

Documentation here

Doug T.
+2  A: 

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>";
?>
Atli
@Atli: Nice picture! :)
Carlos Lima
Thanks. Right back at 'ya! :)
Atli
+5  A: 

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>';
Gumbo
You could also remove the if and do $columns = isset($resultset[0])? array_keys($resultset[0]): array(); outside of the loop :)
Carlos Lima
Hi thanks, great idea, better than to use mysql_fetch_field field but I voted for the post below as it is direct answer to my question :)
programmernovice