mysqli 取出数据库中某表的表头和内容

时间:2023-03-09 07:57:20
mysqli 取出数据库中某表的表头和内容
  • 需求如题

取出数据库中某表的表头和内容,并显示该表的行数和列数

 <?php
//显示表内容的函数
function showTable($tableName){
//连接数据库
$mysqli=new MySQLi("localhost","root","root","test");
if(mysqli_connect_error()){
die(mysqli_connect_error());
}
//设置字符集
$mysqli->query("set names utf8");
//sql查询语句
$sql="select * from $tableName";
//执行sql语句
$res=$mysqli->query($sql);
//取结果集中的行数
$rows=$res->num_rows;
//取结果集中的列数
$colums=$res->field_count;
echo "该表有 $rows 行 $colums 列";
//输出表头
echo "<table border=1 cellspacing=0 cellpadding=3><tr>";
while($field=$res->fetch_field()){
echo "<th>{$field->name}</th>";
}
echo "</tr>";
//输出表的内容
while($row=$res->fetch_row()){
echo "<tr>";
for($i=0;$i<$colums;$i++){
echo "<td>$row[$i]</td>";
}
echo "</tr>";
}
echo "</table>";
//释放结果集
$res->free_result();
//关闭连接
$mysqli->close();
}
showTable("user1");
?>

结果如下:

mysqli 取出数据库中某表的表头和内容