So I have one tiny problem with a script I've been writing to run anytime an admin clicks the backup button.
The functionality is to backup every table in a database, and save them as individual .sql files.
I have been able to create the directory to put them in and even the .sql files themselves, but I can't seem to get it to write to the file.
I would even settle for a one file dump of the entire database, I just need to save it somehow, either to the server or download it to the local machine.
Here is my code.
if(isset($_GET['perform_backup'])) {
$site_connection = mysqli_connect("$db_host", "$db_user_dec", "$db_password_dec", "$db_name_dec") or die("Error Connecting: $DB_ERROR | " . mysqli_error($site_connection));
$web_output .= 'Connected... ' . mysqli_get_host_info($site_connection) . "\n";
if(!$site_connection) {
$web_output .= "Error 12: Unable to connect to MySQL." . PHP_EOL;
$web_output .= "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
$web_output .= "Debugging error: " . mysqli_connect_error() . PHP_EOL;
} else {
$tableList = array();
$SHOW_TABLES=$site_connection->query("SHOW TABLES FROM $set_db_name") or die("Error 12: " . mysqli_error($site_connection));
$SHOW_TABLES_total = $SHOW_TABLES->num_rows;
if($SHOW_TABLES_total != 0) {
while($row2=mysqli_fetch_assoc($SHOW_TABLES)) {
//$table = $row2[0];
//$web_output .= "[$table] <br />";
$directory_ctr = 0;
$dir_name_backup_new = "site_files/$set_directory_name/backups/$current_date_stamp";
if(is_dir($dir_name_backup_new)) {
$web_output .= "'$dir_name_backup_new' exists.";
$web_output .= "<br />";
} else {
$web_output .= "'$dir_name_backup_new' directory does not exist. <br />";
$web_output .= "Attempting To Create Directroy ... <br />";
mkdir("$dir_name_backup_new");
if(is_dir($dir_name_backup_new)) {
$web_output .= "Success Making Directory!";
} else {
$web_output .= "Failed To Make Directory!";
$directory_ctr++;
}
$web_output .= "<br />";
}
if($directory_ctr == 0) {
foreach($row2 as $key=>$table_name) {
$web_output .= "[$table_name] - ";
$backup_file = "$dir_name_backup_new/$current_date_stamp-$table_name.sql";
$web_output .= "$backup_file <br />";
fopen("$backup_file", "w+");
//$db_stmt = $site_connection->query("SELECT * FROM $table_name");
$db_stmt = $site_connection->query("SELECT * INTO OUTFILE '$backup_file' FROM $table_name");
if(!$db_stmt) {
$web_output .= "Could not take data backup... Error: ".$site_connection->error;
} else {
$web_output .= "Backed-up data successfully.";
}
$web_output .= "<br />";
}
} else {
$web_output .= "Error: Directories Not Created. <br />";
}
}
}
}
echo $web_output;
}