Edmonds Commerce : Web Development, Design, SEO

MySQL Dump Partial Restore - Split MySQL Dump into Tables

April 9th, 2008
Read More mysql, php

MySQL dumps are often used as a quick and easy way of backing up an entire MySQL database in one go. However, they are only really designed to restore whole databases as well. So what if you only want to restore certain tables?

I have written this nice little PHP script which will take your dump file and split it into lots of little sql files - one for each table. You can then restore which ever tables you want.

Simply create a php file in the same directory as your dump file. Name it something easy to remember. Then go to it in your web browser, input the name of the dump file and click go.

As this is a fairly massive task (depending on the size of your dump file) you may find it works better on your local test server with some generous php_ini settings for max_execution_time etc.

PHP:
  1. <?php
  2. /*MySQL Dump Split to Tables
  3. * script supplied by Edmonds Commerce
  4. * www.edmondscommerce.co.uk
  5. * if you like it, please link back with a do-follow
  6. */
  7. echo '<h1>MySQL Dump Split to Tables</h1>';
  8. if(!isset($_GET['dump_file'])){
  9.     echo '<form><b>Dump File Path:</b> <input name="dump_file"> <input type="submit" value="go"></form>';
  10. }else{
  11.     $handle = @fopen($_GET['dump_file'], "r");
  12.     if ($handle) {
  13.         while (!feof($handle)) {
  14.             $line = fgets($handle);
  15.             if(strstr($line, 'CREATE TABLE')){
  16.                 if(isset($out)){
  17.                     fclose($out);
  18.                     unset($out);
  19.                 }
  20.                 preg_match('%CREATE TABLE `(.+?)`%', $line, $matches);
  21.                 $table_name = $matches[1];
  22.                 $out = fopen($table_name . '.sql', 'w');
  23.                 fwrite($out, $line . "\n");
  24.             }else{
  25.                 if(isset($out)){
  26.                     fwrite($out, $line . "\n");
  27.                 }
  28.             }   
  29.         }
  30.         fclose($out);
  31.         fclose($handle);
  32.     }   
  33. }
  34. echo '<h1>Done</h1>'
  35. ?>

3 Responses to “MySQL Dump Partial Restore - Split MySQL Dump into Tables”

  1. marius Says:

    Excellent piece of coding. Had an error in the mysqldump that prevented to whole backup from being restored. With your script it was easy to do a partial restore.

    Thanks, Marius

  2. admin Says:

    glad you liked it :-)

  3. Max Says:

    Hey Edmond, thanks for the link. Adds nicely to my blog post on my way of doing partial restore.

Leave a Reply