How to implement database backup and restoration using PDO in PHP?

To implement database backup and restoration using PDO in PHP, you can follow the steps below:

  1. Connect to the database using PDO:
// 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()); }
  1. Backup the database:
// 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."; }
  1. Restore the database:
// 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.