The trick you need is to retrieve the result set's metadata. I refuse to help you do anything with the deprecated and dangerous mysql_ interface, so my answer relates to mysqli_.
Here's documentation.
http://php.net/manual/en/mysqli.quickstart.statements.php
Here's some possible code you could use:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
die "Failed to connect to MySQL: (" .
$mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$res = $mysqli->query("SELECT * FROM table");
if (!$res) {
die "Query failed: (" . $res->errno . ") " . $res->error;
}
$rownumber = 0;
echo "<table>\n";
while ($row = $res->fetch_assoc()) {
if (0 == $rownumber) {
/* first result set row? look at the keys=column nanes */
echo "<tr>";
foreach (array_keys($row) as $colname) {
echo "<td>$colname</td>";
}
echo "</tr>\n";
}
$rownumber ++;
echo "<tr>";
foreach (array_values($row) as $colval) {
echo "<td>$colval</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
$res->close();
As far as reducing the number of times you call "echo", there's no particularly good reason to do that. But if you must you can do something like this to accumulate an output string.
$out = "";
$out .= "<tr>";
foreach (array_values($row) as $colval) {
$out .= "<td>$colval</td>";
}
$out .= "</tr>\n";
echo $out;
$out = "";