nanjero echizen nanjero echizen - 1 year ago 49
SQL Question

PHP - How can I print out my database table?

I have a php code to print out my table including its column name. The printing has to be dynamic because it has to print different size/length tables based on a user input. :

while ($row = mysqli_fetch_array($results)) {
while ($fieldInfo = mysqli_fetch_field($results)) { ?>
<th> <?php echo $fieldInfo->name; ?> </th>
<td> <?php echo $row[$fieldInfo->name] ?> </td>
<?php }
} ?>

this is the query for

$tName = $_POST["tableNames"]; //this data is recieved from another page
$sql = "SELECT * FROM $tName";
$results = mysqli_query($conn, $sql)
or die ('Problem with query' . mysqli_error($conn));

my code correctly prints out the table name as well as the first row data but it is not formatted correctly here is how it looks:

additionally. for some reason it only prints out the first row even though im using a while loop.

Answer Source

My advice to you is to prepare two arrays: First one: containing column names and second: containing data.

When use two foreach to generate first row with header and second one to display data. You have forgot to add <tr> tags to divide rows.