PHP code example of varienos / mysql-backup

1. Go to this page and download the library: Download varienos/mysql-backup library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

varienos / mysql-backup example snippets



Varienos\MySQLBackup\MySQLBackup;

$backup = new MySQLBackup(
    'localhost',      // host
    'username',       // username
    'password',       // password
    'database_name'   // database
);

// Backup all tables
$backup->backup('*');

// Get backup file path
echo "Backup saved to: " . $backup->getLastBackupFile();


Varienos\MySQLBackup\MySQLBackup;

$backup = new MySQLBackup(
    'localhost',
    'username',
    'password',
    'database_name'
);

// Restore from a backup file
$backup->restore('sqlbackup/varienos-sql-backup-mydb-20241010_143000.sql.gz');

$options = [
    'backup_dir' => 'sqlbackup',              // Backup directory
    'charset' => 'utf8mb4',                   // Database charset
    'gzip' => true,                           // Enable gzip compression
    'batch_size' => 2000,                     // Rows per batch
    'disable_foreign_key_checks' => true,     // Disable FK checks during restore
];

$backup = new MySQLBackup($host, $user, $pass, $db, $options);

// Backup specific tables (array)
$backup->backup(['users', 'posts', 'comments']);

// Backup specific tables (comma-separated string)
$backup->backup('users, posts, comments');

$backups = $backup->listBackups();

foreach ($backups as $file) {
    echo "{$file['file']} ({$file['size_formatted']}) - {$file['created_formatted']}\n";
}

$backup->backup('*');

// Get all log entries
$logs = $backup->getLogs();
foreach ($logs as $log) {
    echo $log . "\n";
}



namespace Varienos\MySQLBackup\Tests;

use Varienos\MySQLBackup\MySQLBackup;

class MyCustomTest extends TestCase
{
    public function testMyFeature(): void
    {
        // Create test database and tables
        $this->createTestDatabaseConnection();
        $this->createSampleTables();

        // Insert sample data
        $this->insertSampleData(10, 5);

        // Your test code here
        $backup = new MySQLBackup(
            $this->testDbHost,
            $this->testDbUser,
            $this->testDbPassword,
            $this->testDbName
        );

        $this->assertTrue($backup->backup('*'));
    }
}
bash
   php test-autoload.php
   
bash
   php example-backup.php
   
bash
   php example-restore.php
   
sql
   CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'test_password';
   GRANT ALL PRIVILEGES ON test_backup_db.* TO 'test_user'@'localhost';
   FLUSH PRIVILEGES;
   
bash
./vendor/bin/phpunit tests/MySQLBackupTest.php