mysqli 取出數據庫中某表的表頭和內容

  • 需求如題

取出數據庫中某表的表頭和內容,並顯示該表的行數和列數php

 1 <?php
 2     //顯示錶內容的函數
 3     function showTable($tableName){
 4         //鏈接數據庫
 5         $mysqli=new MySQLi("localhost","root","root","test");
 6         if(mysqli_connect_error()){
 7             die(mysqli_connect_error());
 8         }
 9         //設置字符集
10         $mysqli->query("set names utf8");
11         //sql查詢語句
12         $sql="select * from $tableName";
13         //執行sql語句
14         $res=$mysqli->query($sql);
15         //取結果集中的行數
16         $rows=$res->num_rows;
17         //取結果集中的列數
18         $colums=$res->field_count;
19         echo "該表有 $rows$colums 列";
20         //輸出表頭
21         echo "<table border=1 cellspacing=0 cellpadding=3><tr>";
22         while($field=$res->fetch_field()){
23             echo "<th>{$field->name}</th>";
24         }
25         echo "</tr>";
26         //輸出表的內容
27         while($row=$res->fetch_row()){
28             echo "<tr>";
29             for($i=0;$i<$colums;$i++){
30                 echo "<td>$row[$i]</td>";
31             }
32             echo "</tr>";
33         }
34         echo "</table>";
35         //釋放結果集
36         $res->free_result();
37         //關閉鏈接
38         $mysqli->close();
39     }
40     showTable("user1");
41 ?>

結果以下:mysql

相關文章
相關標籤/搜索