- 需求如题
取出数据库中某表的表头和内容,并显示该表的行数和列数
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 ?>
结果如下: