php不用外接类,导出sql数据:
<?php
header('Content-type: text/html; charset=utf-8');
header("Content-type:application/vnd.ms-excel;charset=UTF-8");
header("Content-Disposition:filename=订单表.xls");
$conn = mysql_connect("localhost","root","123456") or die("不能连接数据库");
mysql_select_db("myfarm", $conn);
mysql_query("set names 'UTF-8'");
$sql="select * from orderlist";
$result=mysql_query($sql);
$title=array_keys(mysql_fetch_array($result,MYSQL_ASSOC));
echo $tit=join($title,"\t")."\n";
while($row=mysql_fetch_array($result,MYSQL_ASSOC)){
echo join(array_values($row),"\t")."\n";
}
?>
第二种方法(PDO):
$title=$pdo->query("show columns from orderlist");
while ($tit=$title->fetchColumn()) {
$tit1.=$tit."\t";
};
echo $tit1."\n";
$sql="select * from orderlist";
$result=$pdo->query($sql);
while($row=$result->fetch(PDO::FETCH_ASSOC)){
echo join(array_values($row),"\t")."\n";
}
写成类:
<?php
session_start();
if (!$_SESSION['adminname']) {
echo "<script>alert('您还没有登录,请先登录!');top.location='/$dirn/admin/login/login.php'</script>";
}
function outFile($titlesql,$contentsql,$fileName){
header('Content-type: text/html; charset=utf-8');
header("Content-type:application/vnd.ms-excel;charset=UTF-8");
header("Content-Disposition:filename=$fileName.xls");
$dirn=dirname(__FILE__);
include("$dirn/public/sql.php");
$title=$pdo->query("$titlesql");
while ($tit=$title->fetchColumn()) {
$allTit.=$tit."\t";
};
echo $allTit."\n";
$result=$pdo->query("$contentsql");
while($row=$result->fetch(PDO::FETCH_ASSOC)){
echo join(array_values($row),"\t")."\n";
}
}
$titlesql="show columns from user";
$contentsql="select * from user";
$fileName="用户表";
outFile($titlesql,$contentsql,$fileName);
?>