I want to display the results of my select query on my webpage in a table, however the code im using at the moment uses a pre-defined set of columns. My code is this:
$result= mysqli_query($con,"SELECT * FROM Customers where First_name = '$specFirstName'");
echo "<table border=\"1px solid black\" width=\"80%\"><tr><th>Customer ID</th><th >First Name</th><th>Last Name</th></tr>" ;
while($row = mysqli_fetch_array($result)){
echo "<tr><td style=\"text-align:center;\">". $row[('CustomerID')] . "</td><td style=\"text-align:center;\">".$row[('First_name')]."</td><td style=\"text-align:center;\">".$row[('Last_name')];
echo "</td></tr>";
}
echo "</table>"
Now, How can I do the same, but use the database headers in an automatically generated table? Can I also use this method to allow the user to specify the required columns in the query? Many thanks, Tommy
Something like this should work. You only have to define the $columns
you want to display in the array map. This also works once you write the code to allow the user to select the columns she/he wants, you will only have to set this map with the selected options.
// Define the columns title and name in this array map.
$columns = array(
'Customer ID' => 'CustomerID',
'First Name' => 'First_name',
'Last Name' => 'Last_name'
);
// Run the query
$result= mysqli_query($con,"SELECT * FROM Customers WHERE First_name = '$specFirstName'");
// Output table header
echo "<table border=\"1px solid black\" width=\"80%\"><tr>";
foreach ($column as $name => $col_name) {
echo "<th>$name</th>";
}
echo "</tr>";
// Output rows
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($column as $name => $col_name) {
echo "<td style=\"text-align:center;\">". $row[$col_name] . "</td>";
}
echo "</tr>";
}
// Close table
echo "</table>"
You can fetch the fields before the while
loop like
$fields = ($result->fetch_fields());
?> <table border="1px solid black" width="80%"><tr> <?php
foreach($fields as $field) {
?> <th><?php echo $field->name; ?></th> <?php
}
?> </tr> <?php
while($row = mysqli_fetch_array($result)){
?><tr><?php
foreach($row as $val) {
?> <td style="text-align: center;"> <?php echo $val; ?> </td> <?php
}
?> </tr> <?php
}
?> </table> <?php