Using mysqldump to Backup a Database

Occasionally I have new clients that don’t have access to their control panel, so that a dump of the database cannot easily be performed from a nice GUI interface (Very useful when I want to setup their site for local development). If the server allows executing mysqldump from in php, the following code can be used to get a dump of the database.

$host = "replace with hostname";
$database = "replace with database name";
$user = "repalce with user name";
$password = "replace with password";

$filename = 'database_backup_'.date('G_a_m_d_y').'.sql';

$result = exec('mysqldump '. $database .' --host='. $host .' --password='. $password .' --user='. $user .' --single-transaction > '. $filename,$output);

Once uploaded to the remote server, you can run the backup from your browser and you should have a dump of the database in the same folder. This can also be adapted to be used with a cron job for automated local backups, but make sure that you change the path of the output so that it is not accessible in the browser.

Scroll to Top