I want to create a html table which will show the values from the mysql array along with their field name for e.g. I have a table with three columns in it and I want to show it all in a table format like:
Name | Age | Telephone |
User | 22 | 1234568098 |
User1 | 22 | 1234568098 |
User2 | 22 | 1234568098 |
User3 | 22 | 1234568098 |
User4 | 22 | 1234568098 |
I want to dynamically count the mysql columns and display them in a html table along with its values.
I know the PHP count()
function and how to create a table in html.
OK here is the solution, I did it only because it's not that trivial (but it's not hard either). Next time post code you tried.
OK, back to question, I did it using PDO, there are other ways out there also. Also I'm echoing HTML from PHP which doesn't look nice, but for simplicity of this problem I would leave it as is.
$sth = $pdo->query("SELECT * FROM users;");
$data = $sth->fetchAll();
echo "<table border='1'>";
echo "<thead>";
for ($i = 0; $i < $sth->columnCount(); $i++) {
$column = $sth->getColumnMeta($i);
echo "<th>" . $column['name'] . "</th>";
}
echo "</thead>";
echo "<tbody>";
foreach($data as $column=>$row)
{
echo '<tr>';
foreach ($row as $key => $value)
{
echo "<td>$value</td>";
}
echo '</tr>';
}
echo "</tbody>";
echo "</table>";