This is the second part of this tutorial. The first part explained all the items on this function and now you are going to see them together.

<?php

$_SESSION[’doThisTables’] = array(); # When the database is too big, you will need a array to hold all tables that can break the script in timeout and execute them later.

function dumpdb($dbserver = ”, $dbuser = ”, $dbpass = ”, $dbdatabase = ”,
$pathToSaveFile = ”, $filename = ”, $printAtScreen = false,
$printScreenOnly = false, $doThisTable = ”){

if(is_string($dbserver) && strlen($dbserver) > 0) {
$server = mysql_escape_string($dbserver);
}
else {
$server = DB_SERVER;
}
if(is_string($dbuser) && strlen($dbuser) > 0) {
$user = mysql_escape_string($dbuser);
}
else {
$user = DB_USERNAME;
}
if(is_string($dbpass) && strlen($dbpass) > 0) {
$pass = mysql_escape_string($dbpass);
}
else {
$pass = DB_PASSWORD;
}
if(is_string($dbdatabase) && strlen($dbdatabase) > 0) {
$db = mysql_escape_string($dbdatabase);
}
else {
$db = DB_DATABASE;
}
if(is_string($pathToSaveFile) && strlen($pathToSaveFile) > 0) {
$pathToSave = mysql_escape_string($pathToSaveFile);
if(is_string($filename) && strlen($filename) > 0) {
$nameToBeUsed = mysql_escape_string($filename);
if(!stristr($nameToBeUsed,’.')) {
$nameToBeUsed .= ‘.sql’;
}
$path = $pathToSave.$nameToBeUsed;
}
else {
$path = $pathToSave.”$db”.”_MySQLDumpAt_”.time().”.sql”;
}
}
else {
if(is_string($filename) && strlen($filename) > 0) {
$nameToBeUsed = mysql_escape_string($filename);
if(!stristr($nameToBeUsed,’.')) {
$nameToBeUsed .= ‘.sql’;
}
$path = SITE_ROOT.”/backups/”.$nameToBeUsed;
}
else {
$path = SITE_ROOT.”/backups/$db”.”_MySQLDumpAt_”.time().”.sql”;
}
}
$byPassTableQuery = false;
if(is_string($doThisTable) && strlen($doThisTable) > 0) {
$tablesToDo = array($doThisTable);
$byPassTableQuery = true;
}
mysql_connect($server, $user, $pass);
mysql_select_db($db);
$tables = false;
if($byPassTableQuery === false) {
$stmt = “SHOW TABLES FROM `$db`”;
$tables = mysql_query($stmt);
}
$sql_dump = “”;
if($tables || $byPassTableQuery === true) {
# $tables = mysql_list_tables($db); <– Deprecated. Using SQL SHOW TABLES instead
if($printScreenOnly === false) {
if(is_file($path) && filesize($path) > 0) {
$filePointer = fopen($path,’a+’); # Opening file to save backup pointing the row for the end of the file
}
else {
$filePointer = fopen($path,’a+’); # Opening file to save backup pointing the row for the beggining of the file
}
}
$tables_array = array(); # for performance and avoiding the script to die in big databases keep the tables in a separate array to control
if($byPassTableQuery === false) {
while($td = mysql_fetch_array($tables)){
$tables_array[] = $td[0];
}
}
else {
$tables_array = $tablesToDo;
}
$tablesSize = sizeof($tables_array);
for($index = 0; $index < $tablesSize; $index++) {
# while($td = mysql_fetch_array($tables)) {
# For each table, create a show create table statement and dump all inserts
$table = $tables_array[$index]; # Getting current table
$showCreates = mysql_query(”SHOW CREATE TABLE `$table`”); # Create table statement
if($showCreates){
$insert_sql = “”; # Cleaning the insert sql string
$d = mysql_fetch_array($showCreates); # retriving the table structure
$d[1] .= “;”; # adding a end statement at the create structure
$createTable = $d[1]; # create statement string
$sql_dump .= $createTable; # for printing at screen
if($printScreenOnly === false) {
fwrite($filePointer,$createTable); # adding create statement in the file
fwrite($filePointer,”\n”); # adding a new line after the create statement
}
$table_query = mysql_query(”SELECT * FROM `$table`”);# getting all rows from the table
$num_fields = mysql_num_fields($table_query); # getting all fields from the table
$num_records = mysql_num_rows($table_query); # checking if the number of rows is too big
if($num_records > 10000 && !in_array($table,$_SESSION[’doThisTables’])) {
$_SESSION[’doThisTables’][] = $table;
}
else {
while($fetch_row = mysql_fetch_array($table_query)){
$insert_sql .= “INSERT INTO $table VALUES(”;
for ($n=1;$n<=$num_fields;$n++){
$m = $n - 1;
$insert_sql .= “‘”.mysql_real_escape_string($fetch_row[$m]).”‘, “;
}
$insert_sql = substr($insert_sql,0,-2);
$insert_sql .= “);\n”; # creating the insert statement for that
}
if ($insert_sql!= “”){
$sql_dump .= $insert_sql; # adding the insert statement to the sql dump string
if($printScreenOnly === false) {
fwrite($filePointer,$insert_sql); # writing the insert statement at file
}
}
}
}
}
if($printScreenOnly === false) {
fclose($filePointer); # closing the file
}
}
if($printAtScreen === true) {
return $sql_dump;
}
else {
return true;
}
}
$pathToSaveFile = SITE_ROOT.’/backups/’;
$filename = DB_DATABASE.’_’.date(’m-d-Y-H-i-s’).’.sql’;
$sql = array();

# If you are testing and needs to print the script on the page uncomment the following lines
/*
********************************************************************************
$dbdatabase = DB_DATABASE;
$dbserver = DB_SERVER;
$dbuser = DB_USERNAME;
$dbpass = DB_PASSWORD;
mysql_connect($dbserver,$dbuser,$dbpass);
mysql_select_db($dbdatabase);
$stmt = “SHOW TABLE STATUS FROM `$dbdatabase`”;
$sqlHandler = mysql_query($stmt);
$rows = 0;
while($result = mysql_fetch_assoc($sqlHandler)) {
$rows += (int) $result[’Rows’];
}
if($rows > 200000) {
$maxTime = ini_get(’max_execution_time’);
if($maxTime <= 120) {
$timeExec = (int) floor($rows/500);
ini_set(’max_execution_time’,$timeExec); # Just in case it needs more time
ini_set(’memory_limit’,'96M’);
}
}
***********************************************************************************
*/
$dump = dumpdb($dbserver = ”, $dbuser = ”, $dbpass = ”, $dbdatabase = ”, $pathToSaveFile, $filename, $printAtScreen = false,
$printScreenOnly = false, $doThisTable = ”);
$sql[] = $dump;
$sizeof = sizeof($_SESSION[’doThisTables’]);
if($sizeof > 0) {
for($index = 0; $index < $sizeof; $index++) {
$table = $_SESSION[’doThisTables’][$index];
$dump = dumpdb($dbserver = ”, $dbuser = ”, $dbpass = ”, $dbdatabase = ”, $pathToSaveFile,
$filename, $printAtScreen = false, $printScreenOnly = false, $table);
$sql[] = $dump;
}
}
unset($_SESSION[’doThisTables’]);
?>

[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]


Comments

Trackbacks

  1. Tired Robot » Blog Archive » Creating a MySQL Dump with PHP Part I

Leave a Comment

You must be logged in to post a comment.

blank