Q:

How to extract column names and and entires on php from mysql with column names displaying only once

I am trying to extract a table from mysql in php with the column names to be used as headers and the values in the column to be displayed as values.

| id | firstname | lastname |
|  1 | Joe       | Jones    |
|  2 | Cal       | Clark    |
|  3 | Rob       | Robin    |

problem is i am getting back     

| id | firstname | lastname |
|  1 | Joe       | Jones    |
| id | firstname | lastname |
|  2 | Cal       | Clark    |
| id | firstname | lastname |
|  3 | Rob       | Robin    |

please help with what i am doing wrong.
P.S I am quite new to programming also don't mind the poor html.
$query = "SELECT * ";
$query .= "FROM {$selected_table} ";
$query .= "LIMIT 0, 30";

$confirmed_query = confirm_query($query);
$query = mysql_query($confirmed_query);

echo "<table>";
while ($query_result = mysql_fetch_assoc($query)) {
    echo "<tr>";
    foreach ($query_result as $columns => $rows) {
        echo "<th>{$columns}</th>";
    }
    echo "</tr><tr>";
    foreach ($query_result as $colums => $rows) {
        echo "<td>$rows</td>";
    }
    echo "</tr>";

}
echo "</table>";

is there any other way to get the column names out of the array with out using a foreach which will cause it to return the column names for each record in the array?

A:

This is a job for do...while!
$query_result = mysql_fetch_assoc($query);
if ($query_result) {
  echo "<table>";
  echo "<tr>";
  foreach ($query_result as $columns => $rows) {
      echo "<th>{$columns}</th>";
  }
  echo "</tr>";
  do {
    echo "<tr>";
    foreach ($query_result as $colums => $rows) {
        echo "<td>$rows</td>";
    }
    echo "</tr>";
  } while ($query_result = mysql_fetch_assoc($query));
  echo "</table>";
}

But I also give +1 to @outis's answer because we should all be using PDO -- not the antiquated and inferior mysql extension.

