seancojr
2/12/2012 - 7:41 AM

Dump every table from every database into its own sql file (Fancy PHP version)

Dump every table from every database into its own sql file (Fancy PHP version)

#!/usr/bin/php
<?php

  // Install these with PEAR
  require_once 'Console/CommandLine.php';
  require_once 'Console/Color.php';
  require_once 'Console/ProgressBar.php';

  define('NL', "\n");


  /**
   * Get the tables in the current database
   *
   * @return void
   **/
  function get_tables($database_name) {
    $tables = array();
    $result = mysql_query('SHOW TABLES FROM ' . $database_name) or die(mysql_error());

    while($row = mysql_fetch_row($result)) {
      $tables[] = $row[0];
    }
    return $tables;
  }


  /**
   * undocumented function
   *
   * @return void
   **/
  function prompt_silent($prompt = "Enter Password:") {
    $command = "/usr/bin/env bash -c 'echo OK'";
    if(rtrim(shell_exec($command)) !== 'OK') {
      trigger_error("Can't invoke bash");
      return;
    }
    $command = "/usr/bin/env bash -c 'read -s -p \""
      . addslashes($prompt)
      . "\" mypassword && echo \$mypassword'";
    $password = rtrim(shell_exec($command));
    echo NL;
    return $password;
  }


  $parser = new Console_CommandLine(array(
    'description' => 'This tool creates a dump of each table in your database in separate files',
    'version'     => '0.0.1', // the version of your program
  ));

  // Adding a simple option that takes no argument and that tell our program to
  // turn on verbose output:
  $parser->addOption(
    'verbose',
    array(
      'short_name'  => '-v',
      'long_name'   => '--verbose',
      'description' => 'turn on verbose output',
      'action'      => 'StoreTrue'
    )
  );

  $parser->addOption(
    'host',
    array(
      'short_name'  => '-h',
      'long_name'   => '--host',
      'description' => 'host with the database',
      'action'      => 'StoreString',
      'default'     => 'localhost'
    )
  );

  $parser->addOption(
    'database',
    array(
      'short_name'  => '-d',
      'long_name'   => '--database',
      'description' => 'name of the database to dump',
      'action'      => 'StoreString'
    )
  );

  $parser->addOption(
    'username',
    array(
      'short_name'  => '-u',
      'long_name'   => '--username',
      'description' => 'user with access to the database',
      'action'      => 'StoreString'
    )
  );

  $parser->addOption(
    'password',
    array(
      'short_name'  => '-p',
      'long_name'   => '--password',
      'description' => 'log in with a password',
      'action'      => 'StoreTrue'
    )
  );

  try {
    $result = $parser->parse();
  } catch (Exception $exc) {
    $parser->displayError($exc->getMessage());
  }

  if(empty($result->options['database'])) {
    echo Console_Color::convert('%RConnection error:%n Database is required.');
    echo NL . NL;
    exit();
  }

  if($result->options['password'] == 1) {
    $password = prompt_silent();
  } else {
    $password = NULL;
  }

  $link = @mysql_connect($result->options['host'], $result->options['username'], $password);
  if(!$link) {
    echo Console_Color::convert('%RConnection error: %n');
    echo 'Could not connect: ' . mysql_error() . NL . NL;
    exit();
  }

  $db = @mysql_select_db($result->options['database'], $link);
  if(!$db) {
    echo Console_Color::convert('%RConnection error: %n');
    echo 'Could not select database: ' . mysql_error() . NL . NL;
    exit();
  }

  $tables = get_tables($result->options['database']);

  $time = time();

  echo 'Writing dumps to disk...';
  $bar = new Console_ProgressBar('  [%bar%] %percent% Elapsed: %elapsed% ETA: %estimate%', '=>', ' ', 80, count($tables));

  $i = 0;
  foreach($tables as $table) {
    $command = 'mysqldump --opt -h ' . $result->options['host'] . ' -u ' . $result->options['username'] .
               ' --password=' . $password . ' ' .  $result->options['database'] . ' ' . $table . ' > ' .
               $table . '_' . $time . '.sql' . NL;
    `$command`;
    $bar->update(++$i);
  }

  echo NL . NL;
  echo Console_Color::convert('%gDumped ' . count($tables) . ' to text files.%n');
  echo NL . NL;