Aug
30

Export from MySQL to Excel using PHP

PHP, SQL          Trackback

Did you ever wanted to export data from your MySQL database to some format nongeek people can work with? Here is simple PHP script you can use to export your data form MySQL table to Excel file. (Actually not real Excel XLS file but CSV file which Excel can read)
Download

/*
Export MySQL to Excel using PHP
Author: Vlatko Zdrale, http://blog.zemoon.com

Look but don't touch :)
*/

	$dbHost	= 'myserver';		//	database host
	$dbUser	= 'myusername';		//	database user
	$dbPass	= 'mypassword';		//	database password
	$dbName	= 'mydatabase'; 	//	database name
	$dbTable = 'mytable';

	$connection = @mysql_connect($dbHost, $dbUser, $dbPass) or die("Couldn't connect.");
	$db = mysql_select_db($dbName, $connection) or die("Couldn't select database.");

	$sql = "Select * from $dbTable";
	$result = @mysql_query($sql) or die("Couldn't execute query");

	header('Content-Type: application/vnd.ms-excel');	//define header info for browser
	header('Content-Disposition: attachment; filename='.$dbTable.'-'.date('Ymd').'.xls');
	header('Pragma: no-cache');
	header('Expires: 0');

	ffor ($i = 0; $i < mysql_num_fields($result); $i++) // show column names
		echo mysql_field_name($result, $i)."\t";
	print("\n");

	while($row = mysql_fetch_row($result))
	{
		//set_time_limit(60); // you can enable this if you have lot of data
		$output = '';
		for($j=0; $j

No Comments

Make A Comment

No comments yet.

Comments RSS Feed    TrackBack URL

Leave a comment

top