0

I'm trying to create a script to create a dump of a mysql database, however, I can't get it working. Below is the code I'm suing.

    $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);
    }

But it's not working...and I know I have some of the code wrong, such as what tables to select (I want to select all the tables).

2
  • 1
    Why don't you dump it in the terminal? Commented Jul 29, 2011 at 0:18
  • Because I'm creating a custom "server control panel", and I need an easy way to back up a predefined database. Commented Jul 29, 2011 at 0:35

1 Answer 1

2

Below might be an easier way to backup your database without having to process all the information. Since it is a MySQL statement, it will probably also run blazingly fast.

From here:
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';  
?>  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.