PHP连接mysql数据库导出csv文件
efbb
9年前
在实际开发中需要经常将数据库中的数据以csv文件的方式导出,这里使用PHP连接mysql,实现CSV格式文件数据的导出功能
我的数据库设计为以下这样:
我的程序代码为:
<?php $action = $_GET['action']; if ($action=='export') { //导出CSV $link = mysql_connect('localhost','root','123456') or die(mysql_error()); mysql_query('set names utf8'); mysql_select_db('stu'); $result = mysql_query("select * from student order by id asc"); $str = "姓名,性别,年龄\n"; //$str = iconv('utf-8','gb2312',$str); while($row=mysql_fetch_array($result)){ $name = iconv('utf-8','gb2312',$row['name']); //中文转码 $gender = iconv('utf-8','gb2312',$row['gender']); $str .= $name.",".$gender.",".$row['age']."\n"; //用引文逗号分开 } $filename = date('Ymd').'.csv'; //设置文件名 export_csv($filename,$str); //导出 } function export_csv($filename,$data) { header("Content-type:text/csv"); header("Content-Disposition:attachment;filename=".$filename); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); echo $data; exit; } ?> <input type="button" class="btn" value="导出CSV文件"> <script language="JavaScript" src="../jquery/jquery-1.4.2.min.js" type="text/javascript"> </script> <script type="text/javascript"> $(".btn").click(function(){ // var year = $("#year option:selected").val(); // var month = $("#month option:selected").val(); // url = '&year='+year+'&month='+month; window.location.href = 'csv.php?action=export'; }) </script>
最后实现的效果为: