您的位置:首页 > 编程语言 > PHP开发

php原生态导出数据库文件

2017-02-10 15:58 288 查看

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);
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据库 php mysql