+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: Using PHP to backup and load Mysql DB

  1. #1
    Gauze is offline x10Hosting Member Gauze is an unknown quantity at this point
    Join Date
    Jun 2008
    Posts
    12

    Using PHP to backup and load Mysql DB

    Is there a way to create a backup of my two mysql's db using PHP script or even over FTP?

    And then import the data into another mysql's?

  2. #2
    gomarc's Avatar
    gomarc is offline x10 Elder gomarc is an unknown quantity at this point
    Join Date
    Oct 2007
    Location
    USA
    Posts
    511

    Re: Using PHP to backup and load Mysql DB

    If this is sort of a one time thing, the easiest way is to go to your cPanel > Backup wizard.

    If you what to schedule this to be done on a regular basis, then you may want to look into cron jobs.

  3. #3
    Gauze is offline x10Hosting Member Gauze is an unknown quantity at this point
    Join Date
    Jun 2008
    Posts
    12

    Re: Using PHP to backup and load Mysql DB

    That's the issue. My CPanel has been down for a long time now and I want to back it up just in case. I do have FTP access still though.

  4. #4
    gomarc's Avatar
    gomarc is offline x10 Elder gomarc is an unknown quantity at this point
    Join Date
    Oct 2007
    Location
    USA
    Posts
    511

    Re: Using PHP to backup and load Mysql DB

    This tutorial may help you: Using PHP to Backup MySQL Databases



  5. #5
    Gauze is offline x10Hosting Member Gauze is an unknown quantity at this point
    Join Date
    Jun 2008
    Posts
    12

    Re: Using PHP to backup and load Mysql DB

    Thank you very much. It does look very promising.
    Edit:
    Bah, method one doesn't seem to show any results and method two doesn't work since system is disabled for security reasons.
    Last edited by Gauze; 06-27-2009 at 11:24 AM. Reason: Automerged Doublepost

  6. #6
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: Using PHP to backup and load Mysql DB

    Only admin accounts would have permission allowing INTO OUTFILE, also for security reasons. You can use a normal SELECT * FROM <table> and have your script format and save the results itself. More work for you, but not much more.

    If you want a full, completely automated backup, start with a SHOW TABLES to get all the tables, then issue a SHOW CREATE TABLE <table> and SELECT * FROM <table> for each table and save the results.
    Last edited by misson; 06-27-2009 at 11:53 AM.
    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

  7. #7
    garrettroyce's Avatar
    garrettroyce is offline Generally Helpful Member garrettroyce is a glorious beacon of lightgarrettroyce is a glorious beacon of light
    Join Date
    Apr 2008
    Location
    IL, USA
    Posts
    3,746

    Re: Using PHP to backup and load Mysql DB

    Maybe this will work:

    Code:
    see newer version below
    A couple of things:
    This does not create the table structures, only copies data into existing tables.
    This does not check if the data is already in the table. If you don't empty the table first, you will have duplicates.
    Last edited by garrettroyce; 06-27-2009 at 01:56 PM.
    gjr.gr - coming soon: secrets of OCD coding from a self taught tinkerer

  8. #8
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: Using PHP to backup and load Mysql DB

    SELECT TABLE_NAME FROM TABLES will include tables that you don't want to back up and doesn't tell you which database each table is in. You could use SELECT TABLE_SCHEMA, TABLE_NAME FROM TABLES to get the database and table or select a database and use SHOW TABLES.

    A multi-value INSERT is more efficient. Here's a scrap based on garrettroyce's code that generates a single INSERT for each table.
    PHP Code:
    ...
    $today strftime('%Y%m%d');
    $backupName "backup-$today.sql";
    if (! (
    $backupFile fopen($backupName'w'))) {
        exit(
    1);
    }
    chmod($backupName0600);
    mysql_select_db('change me!');  // ******Change this to your database name
        
    ...
        
    fwrite($backupFile"INSERT INTO $row[0] VALUES ";
        if (
    $tableRow mysql_fetch_row()) {
            
    // write the first row; no leading comma
            
    $values implode("', '"array_map('mysql_escape_string'$tableRow));
            
    fwrite($backupFile"('$values')" );
        }
        while(
    $tableRow mysql_fetch_row()) { // loop through all table rows
            // write subsequent rows, which have leading commas
            
    $values implode("', '"array_map('mysql_escape_string'$tableRow));
            
    fwrite($backupFile", ('$values')" );
        }
        
    fwrite(";\n");
    }
    fclose($backupFile); 
    The above is untested and needs to be cleaned up.
    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

  9. #9
    garrettroyce's Avatar
    garrettroyce is offline Generally Helpful Member garrettroyce is a glorious beacon of lightgarrettroyce is a glorious beacon of light
    Join Date
    Apr 2008
    Location
    IL, USA
    Posts
    3,746

    Re: Using PHP to backup and load Mysql DB

    Yeah, I went on to do some testing/refining of the code and realized I forgot to add the WHERE to the first query

    Code:
    <?php
    function exportMysql($fileName, $databaseName) {
    	mysql_select_db('INFORMATION_SCHEMA');
    	$file = ''; // this will hold the information
    	$query = "SELECT TABLE_NAME FROM TABLES WHERE TABLE_SCHEMA = '{$databaseName}' AND TABLE_TYPE = 'BASE TABLE'"; // fetch all table names
    	$tableNames = mysql_query($query); // query DB
    	if (!$tableNames) { // if there's an error
    		 exit(mysql_error());
    	}
    	mysql_select_db($databaseName); // select database to back up
    	while($row = mysql_fetch_row($tableNames)) { // loop through all tables
    		 $query = "SELECT * FROM {$row[0]}"; // select everything in the table
    		 $tableData = mysql_query($query); //query DB
    		 if (!$tableData) { // if there's an error
    			  exit(mysql_error());
    		 }
    
    		 while($tableRow = mysql_fetch_row($tableData)) { // loop through all table rows
    			  $data = implode("', '", $tableRow);
    			  $data = "'{$data}'";
    			  $file .= "INSERT INTO {$row[0]} VALUES({$data})\n";
    		 }
    	}
    	file_put_contents($fileName, $file); // save file
    }
    function importMysql($fileName, $databaseName) {
         if (!file_exists($fileName)) {
              exit("File {$fileName} does not exist");
         }
         $file = file_get_contents($fileName);
         $queries = explode("\n", $file);
         mysql_select_db($databaseName);
    
         foreach($queries as $query) {
              mysql_query($query);
         }
    }
    ?>
    That's a good idea:
    Code:
    $values = implode("', '", array_map('mysql_escape_string', $tableRow));
    And also, there is no error checking on the import function, so if a query fails, you won't know. Mission and I could probably go on and on all day perfecting this, but you have a pretty good start
    Last edited by garrettroyce; 06-27-2009 at 01:32 PM.
    gjr.gr - coming soon: secrets of OCD coding from a self taught tinkerer

  10. #10
    Gauze is offline x10Hosting Member Gauze is an unknown quantity at this point
    Join Date
    Jun 2008
    Posts
    12

    Re: Using PHP to backup and load Mysql DB

    Hey, I'm farther ahead than I would be otherwise.

    Thanks a lot.
    Last edited by Gauze; 06-27-2009 at 01:50 PM.

+ Reply to Thread
Page 1 of 2 12 LastLast

Similar Threads

  1. mysql y "Server Load 19.43"
    By cuatropo in forum Soporte
    Replies: 3
    Last Post: 09-03-2008, 10:30 PM
  2. MySQL Issues Here
    By Corey in forum Service Alerts
    Replies: 304
    Last Post: 01-06-2008, 09:10 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers