2016-05-30 11:03

PHP - 如何打印出我的数据库表?


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 $results:

$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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doue9730 doue9730 5年前

    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.

    点赞 评论 复制链接分享
  • dt246813579 dt246813579 5年前

    As of my understand, do you want to display all table and their columns? So you can format like below

    $sql = "SHOW TABLES FROM dbname";
    $result_tables = mysqli_query($link, $sql);
    echo "<table border=1>";
    echo "<tr><td>Table name</td><td>Fields name</td></tr>";
    while($row = mysqli_fetch_array($result_tables)) {
        echo "<tr>";
        echo "<td>".$row[0]."</td>";
        $sql2 = "SHOW COLUMNS FROM ".$row[0];\ow[0] is used to get table name
        $result_fields = mysqli_query($link, $sql2);
        echo "<td>";
        while($row2 = mysqli_fetch_array($result_fields)) {
            echo $row2['Field'].',';
        echo "</td>";
        echo "</tr>";
    点赞 评论 复制链接分享
  • doujia4041 doujia4041 5年前

    I ended up with using a taras' suggestion of storing the column names in an array:

        while ($fieldInfo = mysqli_fetch_field($results)) { ?>
            <th> <?php echo $fieldInfo->name; ?> </th>
            $colNames[] = $fieldInfo->name;
        <?php } 
        while ($row = mysqli_fetch_array($results)) { ?>
            <?php for ($i=0; $i<sizeof($colNames); $i++) { ?>
                <td><?php echo $row[$colNames[$i]] ?>
            <?php } ?>
        <?php } ?>
    点赞 评论 复制链接分享
  • dqd54099 dqd54099 5年前


    The mysqli_fetch_field() function returns the next column in the result set as an object. It will only returns all column names not the records of table.

    You need to use mysqli_fetch_array() for getting all records:

    while ($info = mysqli_fetch_array($results,MYSQLI_ASSOC)) {
      echo $info['rid'];
      echo $info['level'];
    点赞 评论 复制链接分享