Tutorials MySQL Backup MySQL database

Backup MySQL database

Today's tutorial will be how to back up your database. You can create a backup with phpMyAdmin or you can use PHP. This tutorial will show you how to use PHP.

How do you back up?

All you have to do is create a file using this code. Change the database information and run this file on your server. It will create a new .sql file in the same directory.

<?php
// Database information
$dbusername = 'master_admin';
$dbpassword = 'password1234';
$dbname     = 'mysuperdatabase';

// Create file
$backupFile = 'backup'.date("Y_m_d").'.sql';
$command    = 'mysqldump --add-drop-table -u '.$dbusername.' -p'.$dbpassword.' '.$dbname.' > '.$backupFile;
system($command);
?>

How do you restore a backup?

All you have to do is upload your .sql file. Change the database information and the filename. Run this code and it should restore your database.

<?php
// Database information
$dbusername = 'master_admin';
$dbpassword = 'password1234';
$dbname     = 'mysuperdatabase';

// Backup file
$backupFile = 'backup2013_02_01.sql';
$command    = 'mysql -u '.$dbusername.' -p'.$dbpassword.' '.$dbname.' < '.$backupFile;
system($command);
?>

Note: You will need shell access for this to work.

That's it for this tutorial. Remember to backup frequently and don't leave your backups in the open unless you want a major security breach.

Posted by on . Category: MySQL


Comments

No comments posted yet

You need to register or login to post new comments.