Membuat Backup dan Restore MySQL Database di PHP – Bootstrap

Hai All ketemu lagi bersama saya portgastea pria tampan asli sunda he.he.he ,  tutorial kali ini adalah Backup dan Restore MySQL Database di PHP dengan tampilan Bootstrap.

Sangat disarankan untuk membuat backup secara teratur dari database kita, dengan membuat backup akan memungkinkan kita untuk membuat file cadangan untuk berjaga-jaga jika nantinya terjadi kerusakan pada database utama. Pada tutorial cara backup restore database MySQL di PHP ini kita berlatih untuk membuat backup sekaligus restore  tabel dalam database MySQL dengan tampilan bootstrap agar lebih menarik di lihat.

Ok langsung saja kita buat script koneksi ke database seperti dibawah ini

koneksi   
<?php
// definisikan koneksi ke database
$server = "localhost";
$username = "root";
$password = "12345";
$database = "tutorial";
 
// Koneksi dan memilih database di server
mysql_connect($server,$username,$password) or die("Koneksi gagal");
mysql_select_db($database) or die("Database tidak bisa dibuka");
?>

kita buat file index seperti dibawah ini :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Kumpulan Contoh Aplikasi Andeznet</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
 
    <!-- Le styles -->
	    <link href="assets/css/bootstrap.css" rel="stylesheet" media="screen">
        <link href="assets/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen">
		 <link href="assets/css/bootstrap.min.css" rel="stylesheet" media="screen">
 
    <style>
      body {
        padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
      }
    </style>
    <link href="assets/css/bootstrap-responsive.css" rel="stylesheet">
 
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
      <script src="../assets/js/html5shiv.js"></script>
    <![endif]-->
 
    <!-- Fav and touch icons -->
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
      <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
                    <link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
                                   <link rel="shortcut icon" href="assets/ico/logoandeznet.png">
  </head>
 
  <body>
 
   <div class="navbar navbar-inverse navbar-fixed-top">
      <div class="navbar-inner">
        <div class="container">
          <button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="brand" href="http://andeznet.com">AndezNet</a>
          <div class="nav-collapse collapse">
            <ul class="nav">
              <li class="active"><a href="media.php">Home</a></li>
 
				<li class="dropdown">
					<a class="dropdown-toggle" data-toggle="dropdown" href="#">Contoh Aplikasi<b class="caret"></b></a>
				<ul class="dropdown-menu">
				 <li>
                 <a tabindex="-1" href="statistik.php">Statistik Pendaftar</a>
                </li>
				<li>
                 <a tabindex="-1" href="backuprestore.php">Backup Restore</a>
                </li>
				<li>
				<a tabindex="-1" href="carialamat.php">Pencarian Alamat</a>
				</li>
				<li>
				<a tabindex="-1" href="playerbootsrap/index.html">MP3 Player</a>
				</li>
				</ul>
				</li>
 
			  <li><a href="#">About</a></li>
 
              <li>
				<a href="logout.php" id="logout" onclick="return confirm('Apakah Anda yakin?')">
				<i class="ace-icon fa fa-power-off"></i>
				Logout
			</a>
			</li>
            </ul>
          </div><!--/.nav-collapse -->
        </div>
      </div>
    </div>
 
    <div class="container">
 
    </div>
</div>
 
 
 
<!-- Le javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="assets/js/jquery.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
 
 
  </body>
</html>

Sekarang kita buat script PHP untuk backup & restore

<?php
 
                //Download file backup ============================================
                if(isset($_GET['nama_file']))
                {
                    $file = $back_dir.$_GET['nama_file'];
 
                    if (file_exists($file))
                    {
                        header('Content-Description: File Transfer');
                        header('Content-Type: application/octet-stream');
                        header('Content-Disposition: attachment; filename='.basename($file));
                        header('Content-Transfer-Encoding: binary');
                        header('Expires: 0');
                        header('Cache-Control: private');
                        header('Pragma: private');
                        header('Content-Length: ' . filesize($file));
                        ob_clean();
                        flush();
                        readfile($file);
                        exit;
 
                    }
                    else
                    {
                        echo "file {$_GET['nama_file']} sudah tidak ada.";
                    }
 
                }
 
                //Backup database =================================================
                if(isset($_POST['backup']))
                {
                    backup($file);
 
					echo 'Backup database telah selesai <a style="cursor:pointer" href="'.$file.'" title="Download">Download file database</a>';
 
                    echo "<pre>";
                    print_r($return);
                    echo "</pre>";
                }
                else
                {
                    unset($_POST['backup']);
                }
 
                //Restore database ================================================
                if(isset($_POST['restore']))
                {
                    restore($_FILES['datafile']);
 
                    echo "<pre>";
                    print_r($lines);
                    echo "</pre>";
                }
                else
                {
                    unset($_POST['restore']);
                }
 
                ?>
 
 
            <?php
 
            function restore($file) {
                global $rest_dir;
 
                $nama_file	= $file['name'];
                $ukrn_file	= $file['size'];
                $tmp_file	= $file['tmp_name'];
 
                if ($nama_file == "")
                {
                    echo "Fatal Error";
                }
                else
                {
                    $alamatfile	= $rest_dir.$nama_file;
                    $templine	= array();
 
                    if (move_uploaded_file($tmp_file , $alamatfile))
                    {
 
                        $templine	= '';
                        $lines		= file($alamatfile);
 
                        foreach ($lines as $line)
                        {
                            if (substr($line, 0, 2) == '--' || $line == '')
                                continue;
 
                            $templine .= $line;
 
                            if (substr(trim($line), -1, 1) == ';')
                            {
                                mysql_query($templine) or print('Query gagal \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
 
                                $templine = '';
                            }
                        }
                        echo "<center>Berhasil Restore Database, silahkan di cek.</center>";
 
                    }else{
                        echo "Proses upload gagal, kode error = " . $file['error'];
                    }
                }
 
            }
 
            function backup($nama_file,$tables = '')
            {
                global $return, $tables, $back_dir, $database ;
 
                if($tables == '')
                {
                    $tables = array();
                    $result = @mysql_list_tables($database);
                    while($row = @mysql_fetch_row($result))
                    {
                        $tables[] = $row[0];
                    }
                }else{
                    $tables = is_array($tables) ? $tables : explode(',',$tables);
                }
 
                $return	= '';
 
                foreach($tables as $table)
                {
                    $result	 = @mysql_query('SELECT * FROM '.$table);
                    $num_fields = @mysql_num_fields($result);
 
                    //menyisipkan query drop table untuk nanti hapus table yang lama
                    $return	.= "DROP TABLE IF EXISTS ".$table.";";
                    $row2	 = @mysql_fetch_row(mysql_query('SHOW CREATE TABLE  '.$table));
                    $return	.= "\n\n".$row2[1].";\n\n";
 
                    for ($i = 0; $i < $num_fields; $i++)
                    {
                        while($row = @mysql_fetch_row($result))
                        {
                            $return.= 'INSERT INTO '.$table.' VALUES(';
 
                            for($j=0; $j<$num_fields; $j++)
                            {
                                $row[$j] = @addslashes($row[$j]);
                                $row[$j] = @ereg_replace("\n","\\n",$row[$j]);
                                if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                                if ($j<($num_fields-1)) { $return.= ','; }
                            }
                            $return.= ");\n";
                        }
                    }
                    $return.="\n\n\n";
                }
 
                $nama_file;
 
                $handle = fopen($back_dir.$nama_file,'w+');
                fwrite($handle, $return);
                fclose($handle);
            }
            ?>

Sisipkan script php di atas di file index.php setelah <div class=”container”> setelah itu kita jalankan di localhost http://localhost/tutorial , jika sudah benar maka akan tampil seperti gambar di bawah ini .

backup

Untuk restore nya seperti ini

restore with php bootstrap

Ok selesai sudah tutorial kali ini,Untuk Download SourceCode bisa langsung download Aplikasi KSC Ver.1.0.0, di dalamnya ada form login, register,backup,restore & kumpulan soucecode dari Tutorial AndezNET.com saya bagikan GRATIS.

DOWNLOAD

You may also like...

6 Responses

  1. robin says:

    tanya pas restore itu ukurannya kebesaran gmn caranya agar bs suksess restor database gt..

    • portgastea says:

      Berapapun ukuran besar database nya Insya Allah bisa di restore, mungkin membutuhkan waktu agak lama untuk restore dengan ukuran yg besar

  2. Arul says:

    Terima kasih share backup db nya, tapi saya coba ada permasalahan saat download file sql tidak bekerja, tidak langsung download file .sql melainkan ke tab baru.

    • portgastea says:

      coba cari n cek lagi script ini gan
      if(isset($_POST[‘backup’]))
      {
      backup($file);

      echo ‘Backup database telah selesai Download file database‘;

      echo “

      ";
                          print_r($return);
                          echo "

      “;
      }
      else
      {
      unset($_POST[‘backup’]);
      }

  3. Frandy says:

    koc gak bisa di download ya ??

Leave a Reply

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

Hubungi Saya