<?
$hostname = "";
$username = "";
$password = "";
$dbname = "";
mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);
function getTables(){
$result = mysql_query("show tables") or die("can't perform query. ".mysql_error());
while ($row = mysql_fetch_array($result,MYSQL_NUM)):
$tables[] = $row[0];
endwhile;
return $tables;
}
function renderPickerForm(){
$tables = getTables();
$string = '
<form method="post" action="'. $_SERVER['PHP_SELF'] .'">
<fieldset>
<legend>Select tables to export</legend>
<div>
<select name="table">
';
foreach ($tables as $table) {
$string .= '
<option value="'.$table.'">'.$table.'</option>';
}
$string .= "\r\n</select> ";
$string .= '
<input type="checkbox" name="includeHeaders" value="headers" /> Include Headers';
$string .= '</div>';
$string .= '
<div style="margin-top:10px;">
<input type="submit" name="submit" value="export" />
</div>
</fieldset>
</form>';
return $string;
}
function returnTablesToExport() {
if ( !isset ($_POST['table'] ) ) return false;
return array(trim($_POST['table']));
}
function performExport($tables) {
set_time_limit(0);
foreach ($tables as $table):
$cnt = 1;
$filenames[] = "sqlexport_" . $table . md5(uniqid("",true)) . ".csv";
$fh = fopen($filenames[count($filenames)-1], "wbt") or die("cannot open file for writing");
$result = mysql_query("Select * from $table");
while ($row=mysql_fetch_assoc($result)):
$insert = "";
$insert2 = "";
foreach ($row as $key=>$val):
if ($cnt===1 && isset($_POST['includeHeaders'])):
$insert2 .= '"'.addslashes($key).'",';
endif;
$insert .= "\"".addslashes($val)."\",";
endforeach;
if (!empty($insert2)):
fwrite($fh, rtrim($insert2,",")."\n");
$cnt = 2;
endif;
fwrite($fh, rtrim($insert,",")."\n");
endwhile;
fclose($fh);
endforeach;
//$zipFile = zipFiles($filenames);
serveFile($filenames[0]);
}
/*
function zipFiles($filenames){
clearstatcache();
$name = date("Y-m-j"). "-SQL_Export.zip";
require_once "File/Archive.php";
File_Archive::setOption("zipCompressionLevel", 9);
File_Archive::extract(
$filenames,
File_Archive::toArchive(
$name,
File_Archive::toOutput()
)
);
return $name;
}
*/
function serveFile($file) {
header("Cache-Control: ");
header("Pragma: ");
header("Content-Type: application/octet-stream");
header("Content-Length: " .(string)(filesize($file)) );
header('Content-Disposition: attachment; filename="'.$file.'"');
header("Content-Transfer-Encoding: binary\n");
@readfile ($file);
unlink($file);
}
if ( ($tables = returnTablesToExport()) === false):
echo renderPickerForm();
else:
performExport($tables);
endif;
?>