What role does a cron job play in automating database backups in PHP?

To automate database backups in PHP, a cron job can be set up to run a script at specified intervals. This script will connect to the database, create a backup file, and store it in a designated location. By scheduling this cron job to run regularly, you can ensure that your database backups are up to date and easily accessible.

<?php
// Connect to the database
$host = 'localhost';
$username = 'username';
$password = 'password';
$database = 'database_name';
$connection = mysqli_connect($host, $username, $password, $database);

// Create a backup file
$backup_file = 'backup_' . date('Y-m-d') . '.sql';
exec("mysqldump --user={$username} --password={$password} --host={$host} {$database} > {$backup_file}");

// Move the backup file to a designated location
$backup_path = '/path/to/backup/folder/';
rename($backup_file, $backup_path . $backup_file);

// Close the database connection
mysqli_close($connection);
?>