Showing posts with label php mysql db backup. Show all posts
Showing posts with label php mysql db backup. Show all posts

Thursday, 31 July 2014

How to export My Sql Database Backup in php?

$backuptime = "DB_Backup_".DB_NAME."-".time().".sql";
//$backuptime = DB_NAME.".sql";
$data["db_file_name"] = $backuptime;
$insert = $CommonObj->insert_query("db_backup",$data);
$str = "";
$show_tables = "show tables from ".DB_NAME;
$tables = $db->query($show_tables);
if($tables){
   while($row = mysql_fetch_assoc($tables)){
      $table = $row["Tables_in_".DB_NAME];
      $show_each_tables = "show create table ".$table;
      $each_tables  =  $db->query($show_each_tables);
      $each_tables = mysql_fetch_assoc($each_tables);
      $str .= $each_tables["Create Table"];
      $str .= ";\n\n";
      $show_column = "SHOW COLUMNS FROM $table";
      $column  =  $db->query($show_column);
      $get_val_query = "select * from $table";
      $get_val  =  $db->query($get_val_query);
      if($column && mysql_num_rows($get_val)>0){
         $str .= "INSERT INTO `$table` (";
         while($cols = mysql_fetch_assoc($column)){
            $str .= '`'.$cols["Field"].'`, ';
         }
         $str = substr($str,0,-2);
         $str .=  ") VALUES \n";
      }
      if($get_val && mysql_num_rows($get_val)>0){
         while($vals = mysql_fetch_assoc($get_val)){
            $str .= "( ";
            foreach($vals as $k=>$v){
               $v= mysql_real_escape_string($v);
               $str  .= '"'.$v.'", ';
            }
            $str = substr($str,0,-2);
            $str .= "),\n";
         }
         $str = substr($str,0,-2);
      }
      $str .= ";\n\n";
   }
}
$handle = fopen(DIR_DB.$backuptime,'w+');
fwrite($handle,$str);
fclose($handle);