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;
}
try this
$result = $db_con->query('SELECT * FROM `some_table`');
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
Try this out.
$para = array(
'db_host'=> '$DB_HOST', //mysql host
'db_uname' => '$DB_USER', //user
'db_password' => '$DB_PASS', //pass
'db_to_backup' => '$DB_NAME', //database name
'db_backup_path' => './sql-backups/', //where to backup
'db_exclude_tables' => array('') //tables to exclude
);
$dbBackup = new backupDB();
$dbBackup->__backup_mysql_database($para);
class backupDB {
private $params;
function __backup_mysql_database($params) {
date_default_timezone_set("America/New_York");
$tables_array = array();
$contents = "-- Database: `".$params['db_to_backup']."` --\n";
$mysqli = new mysqli($params['db_host'], $params['db_uname'], $params['db_password'], $params['db_to_backup']);
if (!$mysqli) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
//if ($mysqli->connect_error) {
// die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
//}
$show_tables = $mysqli->query("SHOW TABLES");
while($row = $show_tables->fetch_array()){
if (!in_array($row[0], $params['db_exclude_tables'])){
$tables_array[] = $row[0];
}
}
foreach($tables_array as $table){
$contents .= "-- Table `".$table."` --\n";
$show_tables = $mysqli->query("SHOW CREATE TABLE ".$table);
while($row = $show_tables->fetch_array()){
$contents .= $row[1].";\n\n";
}
$show_tables = $mysqli->query("SELECT * FROM ".$table);
$row_count = $show_tables->num_rows;
$fields = $show_tables->fetch_fields();
$fields_count = count($fields);
$insert_head = "INSERT INTO `".$table."` (";
for($i=0; $i < $fields_count; $i++){
$insert_head .= "`".$fields[$i]->name."`";
if($i < $fields_count-1){
$insert_head .= ', ';
}
}
$insert_head .= ")";
$insert_head .= " VALUES\n";
if($row_count>0){
$row_counter = 0;
while($row = $show_tables->fetch_array()){
if(($row_counter % 400) == 0){
$contents .= $insert_head;
}
$contents .= "(";
for($i=0; $i < $fields_count; $i++){
$row_content = str_replace("\n","\\n",$mysqli->real_escape_string($row[$i]));
switch($fields[$i]->type){
case 8: case 3:
$contents .= $row_content;
break;
default:
$contents .= "'". $row_content ."'";
}
if($i < $fields_count-1){
$contents .= ', ';
}
}
if(($row_counter+1) == $row_count || ($row_counter % 400) == 399){
$contents .= ");\n\n";
} else {
$contents .= "),\n";
}
$row_counter++;
}
}
}
if (!is_dir ( $params['db_backup_path'] )) { mkdir ( $params['db_backup_path'], 0777, true ); }
$backup_file_name = $params['db_backup_path']."sql-backup-".date("Y-m-d_H-i-s").".sql";
$fp = fopen($backup_file_name ,'w+');
if (($result = fwrite($fp, $contents))) {
echo "-- Backup file created on ".date("h:i:s a M j, Y")."\n";
}
fclose($fp);
if (file_exists($backup_file_name)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($backup_file_name).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($backup_file_name));
readfile($backup_file_name);
exit;
}
mysqli_close($mysqli);
}
}
Alright, so here is the result I came up with. After using the direction of help from #Pankaj Kaityar's response. I was able to do some more research find a snippet of code that let me make up a function to download a copy of my databases, or save it to the server by the press of one or the other button.
The code is simplified as much as I could, and I'm sure there are other people who could improve this. But this works for me. Anyone else feel free to use it.
//HTML Buttons
Perform Server Backup
Perform Download Backup
//PHP Code
$db_array = array();
$directory_ctr = 0;
$dir_name_backup_new = "site_files/backups/";
if(isset($_GET['perform_new_backup'])) {
include('function_db_export.php');
$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));
echo 'Connected... ' . mysqli_get_host_info($site_connection) . "<br />";
if(!$site_connection) {
echo "Error 12: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
} else {
$SHOW_TABLES=$site_connection->query("SHOW TABLES FROM $db_name_dec") or die("Error 13: " . mysqli_error($site_connection));
$SHOW_TABLES_total = $SHOW_TABLES->num_rows;
if($SHOW_TABLES_total != 0) {
while($row2=mysqli_fetch_assoc($SHOW_TABLES)) {
if(!is_dir($dir_name_backup_new)) {
echo "'$dir_name_backup_new' directory does not exist. <br />";
echo "Attempting To Create Directroy ... <br />";
mkdir("$dir_name_backup_new");
if(is_dir($dir_name_backup_new)) {
echo "Success Making Directory! <br />";
} else {
echo "Failed To Make Directory! <br />";
$directory_ctr++;
}
}
if($directory_ctr == 0) {
foreach($row2 as $key=>$table_name) {
array_push($db_array,"$table_name");
echo "Found '<u>$table_name</u>' Table... Attempting Backup... <br />";
}
} else {
echo "Error: Directories Not Created. <br />";
}
}//END WHILE
//echo print_r($db_array); //Testing Purposes
$new_file_name = $db_name_dec.'-db-backup-'.$current_date_stamp.'.sql';
if($_GET['perform_new_backup'] == "server") {
$save_setting = $save_location=false;
} elseif($_GET['perform_new_backup'] == "download") {
$save_setting = $dir_name_backup_new;
} else {
$save_setting = $dir_name_backup_new;
}
$cur_page = "$select_variable?id=$website_id";
Export_Database($db_host, $db_user_dec, $db_password_dec, $db_name_dec, $save_setting, $table_name = $db_array, $new_file_name, $cur_page);
} //END IF
}
}
//FUNCTION FILE (function_db_export.php)
function Export_Database($host,$user,$pass,$name,$save_location=false, $tables=false, $backup_name=false, $current_page ) {
global $web_output;
$new_conn = new mysqli($host,$user,$pass,$name);
$new_conn->select_db($name);
$new_conn->query("SET NAMES 'utf8'");
$queryTables = $new_conn->query('SHOW TABLES');
while($row = $queryTables->fetch_row()) {
$target_tables[] = $row[0];
}
if($tables !== false) { $target_tables = array_intersect( $target_tables, $tables); }
foreach($target_tables as $table) {
$result = $new_conn->query('SELECT * FROM '.$table);
$fields_amount = $result->field_count;
$rows_num=$new_conn->affected_rows;
$res = $new_conn->query('SHOW CREATE TABLE '.$table);
$TableMLine = $res->fetch_row();
$content = (!isset($content) ? '' : $content) . "\n\n".$TableMLine[1].";\n\n";
for ($i = 0, $st_counter = 0; $i < $fields_amount; $i++, $st_counter=0) {
while($row = $result->fetch_row()) { //when started (and every after 100 command cycle):
if ($st_counter%100 == 0 || $st_counter == 0 ) {
$content .= "\nINSERT INTO ".$table." VALUES";
}
$content .= "\n(";
for($j=0; $j<$fields_amount; $j++) {
$row[$j] = str_replace("\n","\\n", addslashes($row[$j]) );
if (isset($row[$j])) {
$content .= '"'.$row[$j].'"' ;
} else {
$content .= '""';
}
if ($j<($fields_amount-1)) {
$content.= ',';
}
}
$content .=")";
//every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle earlier
if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) {
$content .= ";";
} else {
$content .= ",";
}
$st_counter=$st_counter+1;
}
} $content .="\n\n\n";
}
if($save_location !== false) {
$myfile = fopen($save_location.$backup_name, "w") or die("Unable to open file!");
fwrite($myfile, $content);
fclose($myfile);
$web_output .= "... Backup Has Completed. <br />";
$web_output .= "Page will refresh in 5 seconds.";
header( "refresh:5;url=$current_page" );
} else {
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".$backup_name."\"");
echo $content; exit();
header( "refresh:5;url=$current_page" );
}
}
Related
I have this PHP script which is supposed to take an SQL Query and output it to a CSV file, I know that when I run it i'm getting the right Statement put in but it does not seem to generate a file to my uploads folder.
Could anyone debug this for me?
<?php
function ExportExcel($statement)
{
$filename = "uploads/".strtotime("now").'.csv';
$sql = mysql_query("$statement") or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp, $seperator);
}
fclose($fp);
echo "<a href='$filename'>Download</a>";
echo $statement;
}
else
{
echo "error";
}
}
?>
If someone has a similar script that uses mysqli that would be nice
here is a example of a export script I use on my apps using MySqli. This will get you started...
<?php
function ExportExcel($statement){
$output = "";
$sql = mysqli_query($db , $statement);
$columns_total = mysqli_num_fields($sql);
// Get The Field Name
for ($i = 0; $i < $columns_total; $i++) {
$heading = mysqli_fetch_field_direct($sql, $i);
$output .= '"'.$heading->name.'",';
}
$output .="\n";
// Get Records from the table
while ($row = mysqli_fetch_array($sql)) {
for ($i = 0; $i < $columns_total; $i++) {
$output .='"'.$row["$i"].'",';
}
$output .="\n";
}
// Download the file
$filename = "CSV_NAME_GOES_HERE.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
echo $output;
exit;
}
?>
I am trying to bug fix a PHP script that should export values from a MySQL database to a CSV file.
The PHP file is returning a blank CSV file & I can't figure out why & I've been stuck on this for quite a while, so any help would be much apprwciated.
Code below:
<?
include('../../../inc/config.php');
$period = $_GET['pid'];
$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];
$query="SELECT
sid,
date,
stove_id,
name,
gender,
marital_status,
occupation_of_household,
cz_stove AS km_stove,
happy_with_cz_stove AS happy_with_km_stove,
cz_stove_in_use AS km_stove_in_use,
know_how_to_use,
FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
//header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
hey i have a code you can use it like this
<?PHP
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>
The issue is that you are not writing anything to the csv file before opening it.
Use this code
$fp = fopen($filename, 'w');
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
fputcsv($fp, $headers);
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
header('Content-Type: text/csv');
header( "Content-disposition: filename=".$filename);
readfile($filename);
Thanks to everyone for your suggestions, problem now solved, turned out to be a simple comma in the wrong place - "know_how_to_use," changed to " know_how_to_use" solved the problem. Thanks #Tintu C Raju for pointing me in the right direction
How can I import 200k data faster?
And when I importing csv (delimited by comma) file using online, I got 403 error, and it inserted 200-400 data only. Also when I try to import it using localhost (xampp) i got
"Exception EAccessViolation in module xampp-control.exe at 001AA712.
Access violation at address 005AA712 in module 'xampp-control.exe'.
Read of address 00000042"
And the SQL Database connection is gone.
This is the code I used.
set_time_limit(0);
ignore_user_abort(true);
$file = $_FILES['file']['name'];
$type = $_FILES['file']['type'];
$size = $_FILES['file']['size'];
$temp = $_FILES['file']['tmp_name'];
$error = $_FILES['file']['error'];
if( ! $file)
{
$data['error'] = "Please select a file!";
}
else if($type != "application/vnd.ms-excel" && $type != "application/octet-stream")
{
$data['error'] = "Invalid file type!";
}
else
{
$newname = $file." - ".date("Ymd His");
move_uploaded_file($temp, "uploads/".$newname);
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "uploads/".$newname;
if( ! file_exists($csvfile))
{
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if( ! $file)
{
echo "Error opening data file.";
exit;
}
$size = filesize($csvfile);
if(!$size)
{
echo "File is empty.";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$row = 1;
$data_imported = 0;
$file3 = fopen($csvfile,"r");
$total_file_count = (count(file(FCPATH."/".$csvfile)) - 2);
$i = 0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
while($datas = fgetcsv($file3, 10000, ","))
{
$i++;
ob_implicit_flush(true);
if($row == 1)
{
// Ignore 1st line
}
else
{
$row1 = isset($datas[0]) ? $datas[0] : "";
.
.
to
.
.
$row33 = isset($datas[32]) ? $datas[32] : "";
if($i == 200 OR $total_file_count == $data_imported)
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
);";
}
else
{
$insert .= "(
'".mysqli_real_escape_string($this->db->conn_id(),$row1)."',
.
.
to
.
.
'".mysqli_real_escape_string($this->db->conn_id(),$row33)."'
),";
}
if($i == 200 OR $total_file_count == $data_imported)
{
$this->QModel->query($insert);
$i=0;
$insert = "INSERT IGNORE INTO `invoice`
(`row1`,
.
.
to
.
.
`row33`
) VALUES ";
}
$data_imported++;
}
$row++;
}
fclose($file3);
echo "Success imported ".number_format($data_imported)." data.";
Any ideas?
Thank you.
I have found this code here, and I should use it for my website. But although everything seems fine, somehow delimiter is not working. As you can see, I put comma (,) to be a delimiter and when in mysql there is (|) I put it to be changed to comma again to be separate in cells.
But, I got a result that everything is in first cells. There are commas, but it is not split. So, if I click in excel data > delimiter and split by commas - then it is ok.
How to fix this? I am new, so is there an easy specific change here?
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$columnName = array();
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_assoc($result))
{
$columnName[] = $row['Field'];
$i++;
}
}
$columnName[] .= "\n";
$needle = "|";
$values = mysql_query("SELECT * FROM ".$table." where id=".$id."");
while ($rowr = mysql_fetch_row($values))
{
for ($j=0;$j<$i;$j++)
{
$colName = $columnName[$j];
$count = strlen($rowr[$j]) - strlen(str_replace(str_split($needle), "", $rowr[$j]));
if ($count > 1)
{
for($p=0;$p<$count;$p++)
{
$colName .= ",";
}
$columnName[$j] = $colName;
$csv_output_column_names .= $columnName[$j].", ";
$csv_output_column_values .= str_replace("|",",",$rowr[$j]).", ";
}
else
{
$csv_output_column_names .= $columnName[$j]. ", ";
$csv_output_column_values .= $rowr[$j] .", ";
}
}
$csv_output_column_values .= "\n";
}
$csv_output = $csv_output_column_names."\n".$csv_output_column_values;
$filename = $file."_".date("Y-m-d");
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>
I was asking earlier today about my database backup system
Here's the link: database backup system
Here is the code
if (isset($_POST['getbackup'])) {
/* setcookie("backupdisable", 1, time()*60*60*24); */
$db = "newsite";
$version = "2.3.1";
$date = date('Y-m-d H:i:s');
$final = "-- #".$version."#\n";
$final .= "-- database backup\n";
$final .= "--\n";
$final .= "-- PHP version: ".phpversion()."\n";
$final .= "-- MySQL version: ".mysqli_get_server_info($mysqli)."\n";
$final .= "-- Date: ".date("r")."\n";
$result = $mysqli->query("SHOW TABLE STATUS FROM ".$db);
while ($table = $result->fetch_array()) {
$i = 0;
$result2 = $mysqli->query("SHOW COLUMNS FROM $table[0]");
$z = $result2->num_rows;
$final .= "\n--\n-- DB Export - Table structure for table `".$table[0]."`\n--\n\nCREATE TABLE `".$table[0]."` (";
$prikey = false;
$insert_keys = null;
while ($row2 = $result2->fetch_array()) {
$i++;
$insert_keys .="`".$row2['Field']."`";
$final .= "`".$row2['Field']."` ".$row2['Type'];
if($row2['Null'] != "YES") { $final .= " NOT NULL"; }
if($row2['Default']) $final .= " DEFAULT '".$row2['Default']."'";
if($row2['Extra']) { $final .= " ".$row2['Extra']; }
if($row2['Key'] == "PRI") { $final .= ", PRIMARY KEY (`".$row2['Field']."`)"; $prikey = true; }
if($i < $z){
$final .= ", ";
$insert_keys .=", ";
}
else{
$final .= " ";
}
}
if($prikey) {
if($table[10]) $auto_inc = " AUTO_INCREMENT=".$table[10];
else $auto_inc = " AUTO_INCREMENT=1";
}
else $auto_inc = "";
$charset = explode("_", $table[14]);
$final .= ") ENGINE=".$table[1]." DEFAULT CHARSET=".$charset[0]." COLLATE=".$table[14].$auto_inc.";\n\n--\n-- DB Export - Dumping data for table `".$table[0]."`\n--\n";
$inhaltq = $mysqli->query("SELECT * FROM $table[0]");
while($inhalt = $inhaltq->fetch_array()) {
$final .= "\nINSERT INTO `$table[0]` (";
$final .= $insert_keys;
$final .= ") VALUES (";
for($i=0;$i<$z;$i++) {
$inhalt[$i] = str_replace("'","`", $inhalt[$i]);
$inhalt[$i] = str_replace("\\","\\\\", $inhalt[$i]);
$einschub = "'".$inhalt[$i]."'";
$final .= preg_replace('/\r\n|\r|\n/', '\r\n', $einschub);
if(($i+1)<$z) $final .= ", ";
}
$final .= ");";
}
$final .= "\n";
}
if($logged) {
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Description: File Transfer");
if(is_integer(mb_strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "msie")) AND is_integer(mb_strpos(strtolower($_SERVER["HTTP_USER_AGENT"]), "win" ))) header("Content-Disposition: filename=backup-".strtolower(date("D-d-M-Y")).".sql;");
else header("Content-Disposition: attachment; filename=backup-".strtolower(date("D-d-M-Y")).".sql;");
header("Content-Transfer-Encoding: binary");
echo $final;
exit;
}
}
My question now is this :
The script works just fine, but now im trying to remove the submit button after you get this file so is this possible?
If i refresh the page the button will get removed but i dont know how to do so..
Because if i set a header that refreshes i can't download the file