Skip to content Skip to sidebar Skip to footer

Echo Out All Field Names Along With Their Respective Values

I would like to print a list with all field names and their values from a table in a mysql database. How would i use a loop to print:
FIELD NAME

Solution 1:

This is very basic PHP, a simple while-loop combined with a foreach would suffice:

echo '<table>';
$query = mysql_query("SELECT * FROM `your_table`");
// Loop over all result rows
while($row = mysql_fetch_assoc($query)) {
    // Loop over all fields per row
    foreach($row as $field => $value) {
        echo '<tr><td>' . htmlentities($field) . '</td><td>' . htmlentities($value) . '</td></tr>';
    }
    // New data row can optionally be seperated with a blank line here
    echo '<tr><td colspan="2">&nbsp;</td></tr>';
}
echo '</table>';

Solution 2:

Use mysql_field_name(), mysql_num_fields(), mysql_fetch_field(), mysql_field_seek().

Or keys(mysql_fetch_assoc())


Solution 3:

This is something I did a few days ago:

mysql_connect('localhost','user','password');
mysql_select_db('database');

$sql = "SELECT * FROM  your_table";
$result = mysql_query($sql);

echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
    $meta = mysql_fetch_field($result, $i);   
    echo "<th>".$meta->name."</th>";
    $i++;
}

while ($row = mysql_fetch_row($result))
{
    echo '<tr>';

    foreach($row as $item)
    {
        echo "<td>".$item."</td>";
    }

    echo '</tr>';
}

echo "</table>";

Post a Comment for "Echo Out All Field Names Along With Their Respective Values"