Export MySQL table to CSV

This article will show us how to Export MySql table to csv with one button. Its very simple and requires no coding experience.

First put this form where you want your button to appear:

1
2
3
4
<form action="/process.php" method="post">
	<input type="hidden" name="action" value="export_csv">
	<input type="submit" value="Export CSV">
</form>

 

Step 2:

Now create a file called process.php and paste this into that file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?PHP
/**************************************************************************************************************/
//THIS IS WHERE THE FILE IS EXPORTED
/**************************************************************************************************************/
if($_POST['action'] == "export_csv") {
 
	$host = 'localhost';
	$user = 'mysqlUser';
	$pass = 'myUserPass';
	$db = 'myDatabase';
	$table = 'yourTable';
	$file = 'CSV-EXPORT';
 
	$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
	mysql_select_db($db) or die("Can not connect.");
 
	$result = mysql_query("SHOW COLUMNS FROM ".$table."");
	$i = 0;
 
	if (mysql_num_rows($result) > 0) {
		while ($row = mysql_fetch_assoc($result)) {
			$csv_output .= $row['Field'].", ";
			$i++;
		}
	}
	$csv_output .= "\n";
 
	$values = mysql_query("SELECT * FROM ".$table."");
		while ($rowr = mysql_fetch_row($values)) {
			for ($j=0;$j<$i;$j++) {
				$csv_output .= "'".$rowr[$j]."', ";
			}
		$csv_output .= "\n";
	}
 
	$filename = $file."_".date("Y-m-d_H-i",time());
	header("Content-type: application/csv");
	header("Content-disposition: csv" . date("Y-m-d") . ".csv");
	header( "Content-disposition: filename=".$filename.".csv");
	//print on page if needed.
	//print $csv_output;
	exit;
 
 
 
	}
 
?>

 

Step 3:

Now The only thing left is to edit the variables in process.php, like this:

1
2
3
4
5
6
$host  = 'localhost'; //database address (usually localhost)
$user  = 'mysqlUser'; //database username
$pass  = 'myUserPass'; //database password
$db    = 'myDatabase'; //database name
$table = 'yourTable'; //mysql table to export
$file  = 'CSV-EXPORT'; //filename

 

Yay! that was easy…

It sure was. Happy programming..

 
 
Leave A Reply Here

  Username [*]

  Email Address [*]

  Website

Subscribes to this post comments updates

Please Note: All comments maybe under going moderation so there is no need to resubmit the comments. it will appeared when admin approved it, feel free to subscribes to the post comments rss to stay update