2011-07-29 79 views
0

我想創建一個腳本來創建一個mysql數據庫的轉儲,但是,我不能得到它的工作。以下是我要起訴的代碼。PHP的MySQL轉儲腳本幫助

$file = 'backup_'.substr(md5(TIME_NOW), 0, 10).random_str(30); 
    header('Content-Type: text/x-sql'); 
    header('Content-Disposition: attachment; filename="'.$file.'.sql"');    

    // process backup 
    $time = date('dS F Y \a\t H:i', TIME_NOW); 
    $header = "-- Database Backup\n-- Generated: {$time}\n-- -------------------------------------\n\n"; 
    $contents = $header; 

    $table_selects = array(); 
    $table_list = $db->list_tables($config['database']['database']); 
    foreach($table_list as $id => $table_name) 
    { 
     $table_selects[$table_name] = $table_name; 
    } 

    $field_list = array(); 
    $fields_array = $db->show_fields_from($table_name); 
    foreach($fields_array as $field) 
    { 
     $field_list[] = $field['Field']; 
    }  

    $query = $db->simple_select($table); 
    while($row = $db->fetch_array($query)) 
    { 
     $insert = "INSERT INTO {$table} ($fields) VALUES ("; 
     $comma = ''; 
     foreach($field_list as $field) 
     { 
      if(!isset($row[$field]) || is_null($row[$field])) 
      { 
       $insert .= $comma."NULL"; 
      } 
      else 
      { 
       $insert .= $comma."'".$db->escape_string($row[$field])."'"; 
      } 
      $comma = ','; 
     } 
     $insert .= ");\n"; 
     $contents .= $insert; 
     clear_overflow($fp, $contents); 
    } 

但它不工作...我知道我有一些代碼錯誤,如選擇(我要選擇所有表)哪些表。

+1

你爲什麼不放棄它在終端? – afuzzyllama

+0

因爲我正在創建一個自定義的「服務器控制面板」,所以我需要一種簡單的方法來備份預定義的數據庫。 – Spencer

回答

2

下面可能是一種更簡單的備份數據庫的方法,無需處理所有信息。由於它是MySQL的聲明,它可能也會運行得非常快。

從這裏:
http://www.noupe.com/how-tos/10-ways-to-automatically-manually-backup-mysql-database.html

<?php 
    include 'config.php'; 
    include 'opendb.php'; 

    $tableName = 'mypet'; 
    $backupFile = 'backup/mypet.sql'; 
    $query  = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName"; 
    $result = mysql_query($query); 

    include 'closedb.php'; 
?>