Created
July 17, 2014 08:14
-
-
Save pstaender/4cb358c98fbe8e55ed9d to your computer and use it in GitHub Desktop.
Simple script that creates a MySQL dump of a database. Helpful if you don't have direct access to the database and don't want to use phpmyadmin or the like…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
backup_tables('localhost', 'user', 'passw', 'databasename', '*', true); | |
/* backup the db OR just a table */ | |
function backup_tables($host, $user, $pass, $name, $tables = '*', $filename = null) { | |
$return = ""; | |
$link = mysqli_connect($host, $user, $pass, $name); | |
//get all of the tables | |
if ($tables == '*') { | |
$tables = array(); | |
$result = $link->query('SHOW TABLES'); | |
while ($row = $result->fetch_row()) { | |
$tables[] = $row[0]; | |
} | |
} else { | |
$tables = is_array($tables) ? $tables : explode(',', $tables); | |
} | |
//cycle through | |
foreach ($tables as $table) { | |
$result = $link->query('SELECT * FROM ' . $table); | |
if (!$result) { continue; } | |
$num_fields = $result->field_count; | |
$return .= 'DROP TABLE IF EXISTS ' . $table . ';'; | |
$row2 = $link->query('SHOW CREATE TABLE ' . $table)->fetch_row(); | |
$return .= "\n\n" . $row2[1] . ";\n\n"; | |
for ($i = 0; $i < $num_fields; $i++) { | |
while ($row = $result->fetch_row()) { | |
$return .= 'INSERT INTO ' . $table . ' VALUES('; | |
for ($j = 0; $j < $num_fields; $j++) { | |
$row[$j] = addslashes($row[$j]); | |
$row[$j] = str_replace("\n", "\\n", $row[$j]); | |
if (isset($row[$j])) { | |
$return .= '"' . $row[$j] . '"'; | |
} else { | |
$return .= '""'; | |
} | |
if ($j < ($num_fields - 1)) { | |
$return .= ','; | |
} | |
} | |
$return .= ");\n"; | |
} | |
} | |
$return .= "\n\n\n"; | |
} | |
if ($filename) { | |
if (!is_string($filename)) { | |
$filename = "backup_" . date("d-m-Y") . "_" . $name . ".sql"; | |
} | |
$mime = "text/x-sql"; | |
header( "Content-Type: " . $mime ); | |
header( 'Content-Disposition: attachment; filename="' . $filename . '"' ); | |
} | |
echo $return; | |
} | |
exit(0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment