17
This function takes several parameters:
$host: The MySQL host.$user: The MySQL username.$pass: The MySQL password.$name: The name of the database to be exported.$tables: An optional array of specific tables to export. If not specified, all tables will be exported.$backup_name: An optional name for the backup file. If not specified, a default name will be generated based on the current date and time.
public function exportDatabase($host, $user, $pass, $name, $tables = false, $backup_name = false)
{
set_time_limit(3000);
$mysqli = new mysqli($host, $user, $pass, $name);
$mysqli->select_db($name);
$mysqli->query("SET NAMES 'utf8'");
// Get list of tables
$queryTables = $mysqli->query('SHOW TABLES');
while($row = $queryTables->fetch_row()) {
$target_tables[] = $row[0];
}
// Filter tables if specific tables are provided
if($tables !== false) {
$target_tables = array_intersect($target_tables, $tables);
}
// Initial SQL setup
$content = "-- Database: `$name`\n\n";
foreach($target_tables as $table) {
if (empty($table)) {
continue;
}
// Table structure
$res = $mysqli->query('SHOW CREATE TABLE ' . $table);
$tableMLine = $res->fetch_row();
$content .= "-- Table structure for table `$table`\n";
$content .= $tableMLine[1] . ";\n\n";
// Table data
$result = $mysqli->query('SELECT * FROM `' . $table . '`');
$fields_amount = $result->field_count;
$content .= "-- Dumping data for table `$table`\n";
while($row = $result->fetch_assoc()) {
$content .= "INSERT INTO $table VALUES(";
for($j=0; $j<$fields_amount; $j++) {
$row[$j] = $mysqli->real_escape_string($row[$j]);
$content .= '"' . $row[$j] . '"';
if ($j<($fields_amount-1)) {
$content .= ',';
}
}
$content .= ");\n";
}
$content .= "\n\n";
}
// Set headers for download
$backup_name = $backup_name ? $backup_name : $name . '__' . date('H-i-s') . '_' . date('d-m-Y') . '.sql';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $backup_name . '"');
// Output content
echo $content;
exit;
}
Here's a breakdown of what the function does: