db | Eric's Drupal Blog

Content tagged with: db

Eric's picture

How to dump and compress all mysql databases on a server into separate files using PHP and PEAR

Here's a quick code snippet I just wrote to dump and compress (gzip) all mysql databases on a server into separate files using PHP and PEAR.

<?php
// include PEAR DB library
require_once('DB.php');

// define the DSN in an array
// NOTE: user must have access to all databases
$dsn = array(
 
'phptype' => 'mysql',
 
'username' => 'YOURUSER',
 
'password' => 'YOURPASSWORD',
 
'hostspec' => 'HOSTNAME', // localhost?
);

// instantiate a PEAR DB object
$DB =& DB::connect($dsn);

// check for an error
if (DB::isError($DB)) die($DB->getMessage());

// set the DB fetch mode to associative
$DB->setFetchMode(DB_FETCHMODE_ASSOC);

// define sql statement
$sql = "show databases";

// fetch sql result
$databases = $DB->getAll($sql);

// loop through results
foreach ($databases as $index => $result) {

 
// define the mysqldump command
 
$command = "mysqldump -u " . $dsn['username'] . " "
   
. "-p" . $dsn['password'] . " "
   
. "-h " . $dsn['hostspec'] . " "
   
. $result['Database'] . " | gzip > "
   
. $result['Database'] . ".sql.gz";

 
// execute command
 
`$command`;
   
}
?>

gradient spacer
Eric's picture

Instantiating a PEAR DB class object

Here's common syntax I use for instantiating a PEAR DB class object.

<?php
require_once('DB.php');
$dsn = 'mysql://USER:PASSWORD@HOST/DATABASE';
$DB =& DB::connect($dsn);
if (
DB::isError($DB)) {
  die(
$DB->getMessage());
}
$DB->setFetchMode(DB_FETCHMODE_ASSOC);
?>

gradient spacer Syndicate content