Codice PHP:
<?
include('config.php');
class dump_db
{
var $dir = './out/';
function dump_db()
{
global $host, $user, $pass, $cr_db;
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->cr_db = $cr_db;
if( $this->connetti() == false )
{
die(mysql_error());
}
}
function connetti()
{
if( !($this->db = mysql_connect($this->host, $this->user, $this->pass)) )
{
return false;
}
return true;
}
function dump()
{
$tc = array();
$code = '';
$camp = '';
$db_query = mysql_query("SHOW DATABASES", $this->db) or die(mysql_error());
while( $db = mysql_fetch_array($db_query) )
{
$back = '';
$database = $db[0];
if( $database != 'mysql' )
{
if( $this->cr_db )
{
$back .= "CREATE DATABASE `{$database}`;\n\n";
}
$tbl_query = mysql_query("SHOW TABLES FROM `{$database}`", $this->db) or die(mysql_error());
while( $tbl = mysql_fetch_array($tbl_query) )
{
$table = $tbl[0];
$back .= " CREATE TABLE `{$table}` (\n";
$columns_query = mysql_query("SHOW COLUMNS FROM `{$database}`.`{$table}`", $this->db);
for( $x = 0; $x < mysql_num_rows($columns_query); $x++ )
{
$tb = mysql_result($columns_query, $x);
$campo = $tb;
$spec = mysql_query("SHOW COLUMNS FROM `{$database}`.`{$table}` LIKE '{$campo}'", $this->db);
$spec = mysql_fetch_array($spec);
$back .= ' `'.$campo.'`' . ' ' . $spec['Type'];
$back .= ($spec['Extra'] != '') ? ' '.$spec['Extra'] : '';
$back .= ($spec['Key'] != '') ? ' PRIMARY KEY' : '';
if( $x + 1 != mysql_num_rows($columns_query) )
{
$back .= ',';
}
$back .= "\n";
}
$stat = mysql_query("SHOW TABLE STATUS FROM `{$database}` LIKE '{$table}'", $this->db) or die(mysql_error());
$stat = mysql_fetch_array($stat);
$eng = $stat['Engine'];
$inc = ($stat['Auto_increment'] == '') ? 1 : $stat['Auto_increment'];
$back .= ") ENGINE={$eng} AUTO_INCREMENT={$inc};\n\n";
$colum_query = mysql_query("SHOW COLUMNS FROM `{$database}`.`{$table}`", $this->db) or die(mysql_error());
for( $i = 0; $i < mysql_num_rows($colum_query); $i++ )
{
$campi = mysql_result($colum_query, $i);
$camp .= '`' . $campi . '`';
$tc[] = $campi;
if( $i + 1 != mysql_num_rows($colum_query) )
{
$camp .= ', ';
}
}
$camps = $camp;
$camp = '';
$tot_camp = $tc;
unset($tc);
$query = mysql_query("SELECT * FROM `{$database}`.`{$table}`", $this->db) or die(mysql_error());
while( $row = mysql_fetch_array($query) )
{
$back .= "INSERT INTO `{$table}` (";
$back .= $camps;
$back .= ") VALUES (";
foreach($tot_camp as $k => $v)
{
$back .= "'" . addslashes($row[$k]) . "'";
if( $k + 1 != count($tot_camp) )
{
$back .= ', ';
}
}
$back .= ");\n\n";
}
}
$back .= "\n";
$code .= $back;
$filename = $database . '_' . date('d-m-y');
$this->createfile($filename, $back);
}
}
return $code;
}
function createfile($filename, $content)
{
$fp = fopen($this->dir . $filename . '.sql', 'w+');
fwrite($fp, $content, strlen($content));
fclose($fp);
}
}
$dump = new dump_db();
?>
questo è uno script creato da me che crea un file *.sql per ogni db.
nel file congfig.php ci sono solo le 4 variabili che vengono passate al costruttore.