views:

42

answers:

1

How can we do mysqldump to another DB using php script such that triggers do not get dumped along with that?

+1  A: 

Something like this should work:

$db_name = "db";
$outputfile = "/somewhere";
$new_db_name = 'newdb';

$cmd = 'mysqldump --skip-triggers %s > %s  2>&1';
$cmd = sprintf($cmd, escapeshellarg($db_name), escapeshellcmd($output_file));
exec($cmd, $output, $ret); 
if ($ret !=0 ) {
    //log error message in $output
}

Then to import:

$cmd = 'mysql --database=%s < %s 2>&1';
$cmd = sprintf($cmd, escapeshellarg($new_db_name), escapeshellcmd($output_file));
exec($cmd, $output, $ret); 
//etc.

unlink($outputfile);

Note that the new database will need to be created first. You will also probably need to specify a username and password to each command.

edit

You could also do this in one command e.g.

exec('mysqldump --skip-triggers sourcedb | mysql --database targetdb 2>&1', $output, $return);
Tom Haigh
I am using windows, will exec() and sprintf($cmd, escapeshellarg($db_name), escapeshellcmd($output_file)) function will work here?
OM The Eternity
@OM The Eternity: Yes, I think so.
Tom Haigh
So basically we are creating a file in this code isnit?
OM The Eternity
@OM The Eternity: yes, dumping to a file and then importing from it. you can use something like `tempnam()` to generate a temporary filename.
Tom Haigh
@TOM cant i do this without creating file? Cant I Just use the export Query?
OM The Eternity
@OM The Eternity: yes you can, updated
Tom Haigh