Export MySQL to CSV files with PHP.

CSV files are one of the most used way to backup a MySQL table, and if your hosting have PhpMyAdmin, you probably already know that. Today I’d like to share with you a php script I made. The script calls the database and selects a table. Then it download the content line by line in a csv file. I often try this script when I have to deal with a shared hosting. It is faster than PhpMyAdmin and asks for fewer resources (aka you’ll likely avoid time_out issues).  

< ?php
$host = ''; // < -- db address
$user = 'user'; // < -- db user name
$pass = 'password'; // < -- password
$db = 'db_name'; // db's name
$table = 'table_name'; // table you want to export
$file = 'file_name'; // csv name.

$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'].";";
$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("d-m-Y_H-i",time());

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");

print $csv_output;

via Export MySQL to CSV files with PHP..

Leave a comment

Scroll to Top