繁体   English   中英

从数据库中获取数据并使用php将其显示在表中

[英]Fetch data from database and display it in table using php

很多人会认为这是一个重复的问题并且已经给出了该问题的答案。但是我有一个不同的问题,在这里我不知道列数和列名!

我在html中有一个文本输入类型,用户可以在其中直接操作数据库。 用户可以查询数据库中的任何表。 所有表具有不同的列名和列数。 而且我不能使用'describe'和'show column'sql语句,因为该列的名称未知。

该问题的所有答案都认为程序员已经知道表中的列名和列数。

所以问题是:

  1. 如何获取表中的列数?

  2. 如何获取表的列名以将其显示在表标题标签中?

您可以使用DESC TABLE_NAME

迭代返回以了解字段的数量。

SHOW COLUMNS FROM your_table_name_here使用SHOW COLUMNS FROM your_table_name_here ,当您获取结果时,行数的计数将告诉您有多少列。

返回的部分数据包含在您可用于表标题的列的名称中。

$ColsQ = $yourdb->prepare('SHOW COLUMNS FROM ' . $your_table_name_here);
$ColsQ->execute();
$ColsD = $ColsQ->fetchAll(PDO::FETCH_ASSOC);

echo 'There are ' . count($ColsD) . ' columns in the table';

foreach ($ColsD as $Column) {
    echo 'Column name is ' . $Column['Field'];
}

所以我从php文档中得到了我的问题的答案! 在这里,我将发布执行“选择” SQL语句的代码片段,该语句在运行时执行,该语句显示标头以及我从执行查询得到的结果中的表记录。

      if(strcmp($words[0], "select")==0) //for making sure its select statement
    {
        $result= mysqli_query($conn, $sql);
        if($result)
        {
            echo '<table border=1 style="border-collaspe=collaspe" class="table table-striped table-bordered table-hover dataTable no-footer">';
            echo '<tr>';
            for($i=0;$i<mysqli_num_fields($result);$i++)
            {
                $column_info=mysqli_fetch_field_direct($result, $i); 
               /*this function returns all the information about table metioned in the query.
               variable i over here refers to field no*/
                echo "<th>".$column_info->name."</th>"; //here fetching only name from whole information
            }
            echo '</tr>';
            while ($row = mysqli_fetch_array($result))
            {
                echo '<tr>';
                for($i=0;$i<mysqli_num_fields($result);$i++)
                {
                    echo '<td>'.$row[$i].'</td>';
                }
                echo '</tr>';
            }
            echo '</table>';
        }
        else
        {
            echo "<script>alert('Error occured, Please check your syntax or internet connection')</script>";
        }
    }

有关详细信息: mysqli_fetch_field_direct的PHP文档页面(mysqli_result $ result,int $ fieldnr)函数

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM