To implement database backup and restoration using PDO in PHP, you can follow the steps below:
// Set database connection details
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';
// Establish PDO connection
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected to the database successfully.";
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Set backup file name and path
$backupFile = 'backup_' . date("Y-m-d_H-i-s") . '.sql';
// Execute MySQL command to create a backup
$command = "mysqldump --host=$host --user=$username --password=$password --no-create-info $dbname > $backupFile";
system($command, $output);
if ($output === 0) {
echo "Database backup created successfully.";
} else {
echo "Database backup failed.";
}
// Set restore file name and path
$restoreFile = 'backup.sql';
// Execute MySQL command to restore the database
$command = "mysql --host=$host --user=$username --password=$password $dbname < $restoreFile";
system($command, $output);
if ($output === 0) {
echo "Database restoration completed successfully.";
} else {
echo "Database restoration failed.";
}
Remember to handle file permissions and provide the correct path for the backup and restore files.