Skip to main content

How to backup MySQL Database tables using php

if you want create backup or generate backup file using php, its is very simple and essay understand to everyone. and backup logic is very simple,

Demo link :
http://freeteachnology.hol.es/MysqlBackup/

Code link :
https://drive.google.com/open?id=0BxmTZPVcu72fUjlIRWpUeHlOVzQ

following code demo run as :


One of the most important tasks any developer needs to do often is back up their MySQL database. In many cases, the database is what drives most of the site.

Of course, you'll need to provide database credentials to the function, as well as an array of tables you'd like to backup. If you provide a "*" or no tables, a complete database backup will run. The script does the rest!

In any situation we required a MySQL database tables backup with php scripting. Sometimes its helpful and its very simple to take backup MySQL database tables using php. Easy faster and very simple and clean script for getting your MySQL database backup.

You must have the following details for using the backup MySQL database table script. you should have host name , username ,password and the database name . You can easily customize the script for your requirement and add or remove DROP commands etc.

After setting the required details you will get a file in the current location (where this page running ) .

Yes you have done with backup MySQL database table using php. try it today?


In this article i am going to explore how to download files in php from web server to local machine. Download files in php just a simple process.
You do not need more lines of code to achieve that.
For make easy php works with header to download and read a file.
 For rest of code understanding read code comments of each line of code.

 if you want to create demo then please follow follwoing steps:
 1-header.php
 it include link only bootstrap files and js link,

 Code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>how to backup MySQL Database tables using php
</title>
   <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
   <link href="error.css" rel="stylesheet">
   <script   src="https://code.jquery.com/jquery-3.1.1.js"   integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="   crossorigin="anonymous">
   </script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    <link href="bootstrap-tour.css" rel="stylesheet">
    <script src="bootstrap-tour.js"></script>
</head>
<body>
<!-- start:header -->
<nav class="navbar navbar-default navbar-fixed-top">
  <div class="container-fluid" id="freeteachnology">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">     
      <a class="navbar-brand" href="#">Free Teachnology</a>
    </div>
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home <span class="sr-only"></span></a></li>
        <li><a href="#">About us</a></li>   
        <li><a href="#">Contact us</a></li>         
      </ul>
      </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>

2-footer.php :
footer file link only social website :

Code :
<!-- Start::footer  -->
<footer>
        <div class="footer footer-bottom">
        <div class="container">
            <p class="pull-left"> Copyright © <?php echo date('Y');?>. Design and Develop by - Disuza Jen. </p>
            <div class="pull-right">
                <ul class="nav nav-pills payments">
                    <li>
                    <a  target="blank" href="https://www.facebook.com/profile.php?id=100011576444095">
                    <i class="fa fa-facebook"></i></a>
                    </li>
                    <li>
                    <a target="blank"  href="https://plus.google.com/116407769803493244155">
                    <i class="fa fa-google"></i></a>
                    </li>
                    <li>
                         <a target="blank"  href="https://twitter.com/disuzajen1">
                         <i class="fa fa-twitter"></i></a></li>
                    <li>
                        <a target="blank" href="https://plus.google.com/116407769803493244155">
                    <i class="fa fa-link"></i>
                    </a>
                    </li>
                </ul> 
            </div>
        </div>
    </div>
    <!--/.footer-bottom--> 
</footer>
<!-- End::footer  -->
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css">
</body>
</html>

 3-index.php
index.php files include header and footer link as well as link of action.php files,
following code is very simple and understand no need to extra explaination,

Code :
<?php include('header.php');?>
<!-- end:header -->
<br><br><br>
<style>
#loader {
    bottom: 0;
    height: 175px;
    left: 0;
    margin: auto;
    position: absolute;
    right: 0;
    top: 0;
    width: 175px;
}
#loader {
    bottom: 0;
    height: 175px;
    left: 0;
    margin: auto;
    position: absolute;
    right: 0;
    top: 0;
    width: 175px;
}
#loader .dot {
    bottom: 0;
    height: 100%;
    left: 0;
    margin: auto;
    position: absolute;
    right: 0;
    top: 0;
    width: 87.5px;
}
#loader .dot::before {
    border-radius: 100%;
    content: "";
    height: 87.5px;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
    transform: scale(0);
    width: 87.5px;
}
#loader .dot:nth-child(7n+1) {
    transform: rotate(45deg);
}
#loader .dot:nth-child(7n+1)::before {
    animation: 0.8s linear 0.1s normal none infinite running load;
    background: #00ff80 none repeat scroll 0 0;
}
#loader .dot:nth-child(7n+2) {
    transform: rotate(90deg);
}
#loader .dot:nth-child(7n+2)::before {
    animation: 0.8s linear 0.2s normal none infinite running load;
    background: #00ffea none repeat scroll 0 0;
}
#loader .dot:nth-child(7n+3) {
    transform: rotate(135deg);
}
#loader .dot:nth-child(7n+3)::before {
    animation: 0.8s linear 0.3s normal none infinite running load;
    background: #00aaff none repeat scroll 0 0;
}
#loader .dot:nth-child(7n+4) {
    transform: rotate(180deg);
}
#loader .dot:nth-child(7n+4)::before {
    animation: 0.8s linear 0.4s normal none infinite running load;
    background: #0040ff none repeat scroll 0 0;
}
#loader .dot:nth-child(7n+5) {
    transform: rotate(225deg);
}
#loader .dot:nth-child(7n+5)::before {
    animation: 0.8s linear 0.5s normal none infinite running load;
    background: #2a00ff none repeat scroll 0 0;
}
#loader .dot:nth-child(7n+6) {
    transform: rotate(270deg);
}
#loader .dot:nth-child(7n+6)::before {
    animation: 0.8s linear 0.6s normal none infinite running load;
    background: #9500ff none repeat scroll 0 0;
}
#loader .dot:nth-child(7n+7) {
    transform: rotate(315deg);
}
#loader .dot:nth-child(7n+7)::before {
    animation: 0.8s linear 0.7s normal none infinite running load;
    background: magenta none repeat scroll 0 0;
}
#loader .dot:nth-child(7n+8) {
    transform: rotate(360deg);
}
#loader .dot:nth-child(7n+8)::before {
    animation: 0.8s linear 0.8s normal none infinite running load;
    background: #ff0095 none repeat scroll 0 0;
}
#loader .lading {
    background-image: url("../images/loading.gif");
    background-position: 50% 50%;
    background-repeat: no-repeat;
    bottom: -40px;
    height: 20px;
    left: 0;
    position: absolute;
    right: 0;
    width: 180px;
}
@keyframes load {
100% {
    opacity: 0;
    transform: scale(1);
}
}
@keyframes load {
100% {
    opacity: 0;
    transform: scale(1);
}
}

</style>
<div class="cleafix"></div>
<div class="container">
<div class="alert alert-info">
    <strong>Hi..</strong> how to backup MySQL Database tables using php
</div>
       <div class="alert alert-warning">
        <a href="https://drive.google.com/open?id=0BxmTZPVcu72fUjlIRWpUeHlOVzQ
" class="btn btn-xs btn-warning pull-right" target="blank();">Click</a>
        <strong> Code download link-</strong>
    </div>
     <br><br>  
 </div>
<div class="container">
  <div class="row">     
       <a href="action.php"> 
        <button type="button" class="btn btn-primary" onclick="waitingDialog.show();setTimeout(function () {
          waitingDialog.hide();}, 3000);">Create Backup
        </button>
        </a>
  </div>
</div>
<br><br>  <br><br>  <br><br>  <br><br>  
 <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
</br>
<?php include('footer.php');?>
<script>
/**
 * Module for displaying "Waiting for..." dialog using Bootstrap
 *
 * @author Eugene Maslovich <ehpc@em42.ru>
 */
var waitingDialog = waitingDialog || (function ($) {
    'use strict';
  // Creating modal dialog's DOM
  var $dialog = $(
    '<div class="container"><div class="row"><div id="loader"><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div><div class="dot"></div>      <div class="dot"></div><div class="dot"></div><div class="lading"></div></div></div></div>');

  return {
    /**
     * Opens our dialog
     * @param message Custom message
     * @param options Custom options:
     *          options.dialogSize - bootstrap postfix for dialog size, e.g. "sm", "m";
     *          options.progressType - bootstrap postfix for progress bar type, e.g. "success", "warning".
     */
    show: function (message, options) {
      // Assigning defaults
      if (typeof options === 'undefined') {
        options = {};
      }
      if (typeof message === 'undefined') {
        message = 'Loading';
      }
      var settings = $.extend({
        dialogSize: 'm',
        progressType: '',
        onHide: null // This callback runs after the dialog was hidden
      }, options);

      // Configuring dialog
      $dialog.find('.modal-dialog').attr('class', 'modal-dialog').addClass('modal-' + settings.dialogSize);
      $dialog.find('.progress-bar').attr('class', 'progress-bar');
      if (settings.progressType) {
        $dialog.find('.progress-bar').addClass('progress-bar-' + settings.progressType);
      }
      $dialog.find('h3').text(message);
      // Adding callbacks
      if (typeof settings.onHide === 'function') {
        $dialog.off('hidden.bs.modal').on('hidden.bs.modal', function (e) {
          settings.onHide.call($dialog);
        });
      }
      // Opening dialog
      $dialog.modal();
    },
    /**
     * Closes dialog
     */
    hide: function () {
      $dialog.modal('hide');
    }
  };
})(jQuery);
</script>

loader will be show when click on button and generate mysql backup

5-action.php :

action.php files show or create MySQL backup ,database connection first create and assign new name of file

Code :
<?php
$backup_file = 'db-backup-'.time().'.sql';
 // get backup
 $hostname="localhost";
  $username="";
  $password="";
  $dbname="";
?>
  after that call function backup_tables, function call when check table in exist in database as well as make final array of table and structure,

  Code :
<?php 
  function &backup_tables($host, $user, $pass, $name, $tables = '*'){
  $data = "\n/*---------------------------------------------------------------".
          "\n  SQL DB BACKUP ".date("d.m.Y H:i")." ".
          "\n  HOST: {$host}".
          "\n  DATABASE: {$name}".
          "\n  TABLES: {$tables}".
          "\n  ---------------------------------------------------------------*/\n";
  $link = mysql_connect($host,$user,$pass);
  mysql_select_db($name,$link);
  mysql_query( "SET NAMES `utf8` COLLATE `utf8_general_ci`" , $link ); // Unicode

  if($tables == '*'){ //get all of the tables
    $tables = array();
    $result = mysql_query("SHOW TABLES");
    while($row = mysql_fetch_row($result)){
      $tables[] = $row[0];
    }
  }else{
    $tables = is_array($tables) ? $tables : explode(',',$tables);
  }

  foreach($tables as $table){
    $data.= "\n/*---------------------------------------------------------------".
            "\n  TABLE: `{$table}`".
            "\n  ---------------------------------------------------------------*/\n";           
    $data.= "DROP TABLE IF EXISTS `{$table}`;\n";
    $res = mysql_query("SHOW CREATE TABLE `{$table}`", $link);
    $row = mysql_fetch_row($res);
    $data.= $row[1].";\n";
    $result = mysql_query("SELECT * FROM `{$table}`", $link);
    $num_rows = mysql_num_rows($result);    
    if($num_rows>0){
      $vals = Array(); $z=0;
      for($i=0; $i<$num_rows; $i++){
        $items = mysql_fetch_row($result);
        $vals[$z]="(";
        for($j=0; $j<count($items); $j++){
          if (isset($items[$j])) { $vals[$z].= "'".mysql_real_escape_string( $items[$j], $link )."'"; } else { $vals[$z].= "NULL"; }
          if ($j<(count($items)-1)){ $vals[$z].= ","; }
        }
        $vals[$z].= ")"; $z++;
      }
      $data.= "INSERT INTO `{$table}` VALUES ";      
      $data .= "  ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
    }
  }
  mysql_close( $link );
 return $data;
}
?>

file download function is very simple if create new database file :
Code :
<?php
//start::file downmload fnction:-
$file = $backup_file;
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
//end::file download
?>

following is full code of action.php files :

Code :


<?php 
// create backup
//////////////////////////////////////
ini_set("memory_limit", "-1");
set_time_limit(0);
$backup_file = 'db-backup-'.time().'.sql';
 // get backup
 $hostname="";
  $username="";
  $password="";
  $dbname="";

$mybackup = backup_tables($localhost,$username,$password,$dbname,"*");
// save to file
$handle = fopen($backup_file,'w+');
// chmod($handle, 755);   // decimal; probably incorrect
fwrite($handle,$mybackup);
fclose($handle);
//start::file downmload fnction:-
$file = $backup_file;
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
//end::file download
//create database backup::-
function &backup_tables($host, $user, $pass, $name, $tables = '*'){
  $data = "\n/*---------------------------------------------------------------".
          "\n  SQL DB BACKUP ".date("d.m.Y H:i")." ".
          "\n  HOST: {$host}".
          "\n  DATABASE: {$name}".
          "\n  TABLES: {$tables}".
          "\n  ---------------------------------------------------------------*/\n";
  $link = mysql_connect($host,$user,$pass);
  mysql_select_db($name,$link);
  mysql_query( "SET NAMES `utf8` COLLATE `utf8_general_ci`" , $link ); // Unicode

  if($tables == '*'){ //get all of the tables
    $tables = array();
    $result = mysql_query("SHOW TABLES");
    while($row = mysql_fetch_row($result)){
      $tables[] = $row[0];
    }
  }else{
    $tables = is_array($tables) ? $tables : explode(',',$tables);
  }

  foreach($tables as $table){
    $data.= "\n/*---------------------------------------------------------------".
            "\n  TABLE: `{$table}`".
            "\n  ---------------------------------------------------------------*/\n";           
    $data.= "DROP TABLE IF EXISTS `{$table}`;\n";
    $res = mysql_query("SHOW CREATE TABLE `{$table}`", $link);
    $row = mysql_fetch_row($res);
    $data.= $row[1].";\n";
    $result = mysql_query("SELECT * FROM `{$table}`", $link);
    $num_rows = mysql_num_rows($result);    
    if($num_rows>0){
      $vals = Array(); $z=0;
      for($i=0; $i<$num_rows; $i++){
        $items = mysql_fetch_row($result);
        $vals[$z]="(";
        for($j=0; $j<count($items); $j++){
          if (isset($items[$j])) { $vals[$z].= "'".mysql_real_escape_string( $items[$j], $link )."'"; } else { $vals[$z].= "NULL"; }
          if ($j<(count($items)-1)){ $vals[$z].= ","; }
        }
        $vals[$z].= ")"; $z++;
      }
      $data.= "INSERT INTO `{$table}` VALUES ";      
      $data .= "  ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
    }
  }
  mysql_close( $link );
  return $data;
}
?>

i hope that code is working very code and create backup very fast and esaiy way,if you like my blog plaese comment and share.

Comments

Popular posts from this blog

All CSV data insert into MYSQL database

All CSV data insert into MYSQL database Function name : LOAD DATA LOCAL INFILE eg : # Make database connection :: $mysql = "LOAD DATA LOCAL INFILE 'Nulk-186677.csv' INTO TABLE product_details FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' IGNORE 1 ROWS (@PRODUCT_TITLE,@PRODUCT_DESCRIPTION,@STYLE,@AVAILABLE_SIZES,@BRAND_LOGO_IMAGE,@THUMBNAIL_IMAGE,@COLOR_SWATCH_IMAGE,@PRODUCT_IMAGE,@SPEC_SHEET,@PRICE_TEXT,@PRODUCT_STATUS,@KEYWORDS) SET p_title = @PRODUCT_TITLE, p_desc = @PRODUCT_DESCRIPTION, p_style = @STYLE, p_available_size=@p_available_size, p_brand_logo_image=@p_brand_logo_imagem, p_brand_thumbnail_image=@p_brand_thumbnail_image, p_color_swatch_image=@p_color_swatch_image, p_image=@PRODUCT_IMAGE, p_spec_sheet=@SPEC_SHEET, p_prices_text=@PRICE_TEXT, p_status=@PRODUCT_STATUS, p_keywords=@KEYWORDS"; mysql_query($mysql);

FCM Notification in android and IOS App

Free Teachnology provide free #PHP,#MySql,#Javascript,#jQuery,#API integration,#Payment gateway integration,#Social Media login Firebase Cloud Messaging Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4KB to a client app IOS Setup link : https://firebase.google.com/docs/cloud-messaging/ios/client Andriod Link : https://firebase.google.com/docs/cloud-messaging/android/client Web Link : https://firebase.google.com/docs/cloud-messaging/js/client How does it work? Firebase Cloud Messaging architecture diagram An FCM implementation includes two main components for sending and receiving: A trusted environment such as Cloud Functions for Firebase ...