<?php
//这里三个header文件是为了将数据库数据导出Excel表格中,必须存在;
//设置编码
header(‘Content-type: text/html; charset=utf-8‘);
//设置为Excel
header("Content-type:application/vnd.ms-excel");
//设置Excel表名
header("Content-Disposition:filename=PHP_est.xls");
//面向过程风格,连接数据库事例
$conn = mysqli_connect("localhost", "root", "", "php_test");
//判断连接数据库是否成功
if (mysqli_connect_error($conn)) {
die("连接失败:".mysqli_connect_error());
}
//从MySQL数据库读取数据,设置编码
mysqli_query($conn, "SET NAMES utf8mb4");
$sql = "SELECT * FROM zrzf_student";
//执行sql语句
//$conn->query($sql);这里query是方法,实例对象的方法;
$result = $conn->query($sql);
//这里增加表头
$filename = array("用户ID","名字","年龄","身高");
foreach ($filename as $key => $value) {
//由utf8转为gb2312,防止导出Excel文件汉字乱码问题
$name = mb_convert_encoding($value, "gb2312" , "utf-8" );
echo $name."\t";
}
//Excel表格换行
echo "\n";
if ($result->num_rows > 0) {
//关联数组
while($row = mysqli_fetch_array($result,MYSQLI_NUM)) {
// 存数据
// $dataArr[] = $row;
echo $row[0]."\t".$row[1]."\t".$row[2]."\t".$row[3]."\t\n";
}
}else{
echo "没有查询数据!";
}
$conn->close();