PHP export MySQL data to Excel

Source: Internet
Author: User

Temporary need to export MySQL a table to Excel table, there is a phpexcel plug-in can be used, I feel a bit of trouble, and I was temporarily to backup, I wrote directly.

<?PHP/*connecting to a database*/ $DB _server= "ServerIP"; $DB _username= "UserName"; $DB _password= "PassWord"; $DB _dbname= "DBname";//Target Database name$DB _tblname= "TableName";//Target table name$Connect= @mysql_connect($DB _server,$DB _username,$DB _password) or die("couldn ' t connect.")); mysql_query("Set Names UTF8"); $savename=Date("Ymjhis");//Export Excel file name$file _type= "Vnd.ms-excel"; $file _ending= "xls"; Header("content-type:application/$file _type; Charset=utf-8 "); Header("Content-disposition:attachment; Filename= ".$savename.".$file _ending"); Header("Pragma:no-cache"); /*Write Note Information*/ $now _date=Date("Y-m-j h:i:s"); $title= "Database name:$DB _dbname, Data sheet:$DB _tblname, Backup date:$now _date"; Echo Iconv("Utf-8", "GBK",$title)." \ n "; /*Querying the database*/ $sql= "SELECT * from"$DB _tblname"; $ALT _db= @mysql_select_db($DB _dbname,$Connect) or die("Couldn ' t Select Database"); $result= @mysql_query($sql,$Connect) or die(Mysql_error()); /*Write table field name*/ for($i= 0;$i<Mysql_num_fields($result);$i++) {     Echo Mysql_field_name($result,$i) . "\ T"; }  Echo"\ n";/*Writing table Data*/ $sep= "\ T";  while($row=Mysql_fetch_row($result)) {   $data= "";  for($i= 0;$i<Mysql_num_fields($result);$i++) {     if(!isset($row[$i]))      $data. = "NULL".$sep;//working with null fields   ElseIf($row[$i] != ""){     $datmp=Iconv("Utf-8", "GBK",$row[$i]); $data.=$datmp.$sep; }    Else      $data.= "".$sep;//working with empty fields  }   Echo $data." \ n "; } ?>

Okay, so direct access to this PHP file will allow you to export the data from the specified table.

PHP export MySQL data to Excel

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.