Database backup is an important part of a web site or web application. We need to backup database to keep
our data safe by keeping a copy of the database to my own safe storage. If db crashed or for any reason my current db is not providing me data properly, i the can restore my backup copy of the database.

Database backup in php and mySql

<?php
$con = mysqli_connect("localhost", "root", "", "mydb");
$tables = array();
$query = mysqli_query($con, 'SHOW TABLES');

while ($row = mysqli_fetch_row($query))
{
$tables[] = $row[0];
}

$result = "";

foreach($tables as $table)
{
$query = mysqli_query($con, 'SELECT * FROM ' . $table);
$num_fields = mysqli_num_fields($query);
$result.= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE ' . $table));
$result.= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++)
{
while ($row = mysqli_fetch_row($query))
{
$result.= '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]))
{
$result.= '"' . $row[$j] . '"';
}
else
{
$result.= '""';
}

if ($j < ($num_fields - 1))
{
$result.= ',';
}
}

$result.= ");\n";
}
}

$result.= "\n\n";
}
CreateFolder $folder = 'Backup_Files/';
$date = date('m-d-Y');
$mainname = "db_backup_" . $date . '.sql';
$filename = $folder . $mainname;
echo $filename;
$handle = fopen($filename, 'w+');
fwrite($handle, $result);
fclose($handle);
sendMail($filename, $date, $mainname);

function sendMail($filename, $date, $mainname)
{
$file = $filename;
$mailto = 'mcajoydeb@gmail.com';
$subject = 'Db backup : ' . $date;
$message = 'My message';
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
$separator = md5(time());
carriage return type (RFC) $eol = "\r\n";
main header (multipart mandatory)
$headers = "From: no-reply@jquerytraining.com" . $eol;
$headers .= "MIME-Version: 1.0" . $eol;
$headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
$headers .= "Content-Transfer-Encoding: 7bit" . $eol;
$headers .= "This is a MIME encoded message." . $eol;
$body .= "--$separator\r\n";
$body .="Content-Type: $file_type; name=".$mainname."\r\n";
$body .="Content-Disposition: attachment; filename=".$mainname."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $content ;
SEND Mail if (mail($mailto, $subject, $body, $headers)) {
echo " Email sent with attachment : " .$filename;
} else {
echo "Mail not sent ERROR!"; print_r( error_get_last() ); }
}

?>
admin ajaxurl form front end
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>

Leave comment

Your email address will not be published. Required fields are marked with *.