Sivut

tiistai 13. joulukuuta 2016

MySQL tietokantojen varmistus PHP -koodilla


On aika suutarinkin rakentaa itselle omat kengät.
Tässä tapauksessa automaattinen varmistus tietyille SQL -tietokannoille.

Sitä tarkoitusta varten on maailma tulvillaan koodia, mutta niitä ei vain tule käytettyä tai ehkä ne ovat liian monimutkaisia. Pienten ja keskisuurten tietokantojen varmistamiseen löysin erään mielenkiintoisen PHP -koodin.

Tässä on pieni koodinpätkä varmistusten tekemiseen, joka käyttää backupmysql.class.php kirjastoa. Se taas löytyy otsikossa kerrotusta paikasta.

<?php
/*
 * http://coursesweb.net/php-mysql/simple-backup-mysql-database_s2
 *
 * - Using backupmysql class to create backup of all the tables in mysql database.
 * - Modify for Hotel database, JoH 30.11.2016
 *
 * cron: 0     1     *     *     *
 * wget -qO- -t 1 http://www.hotelli.fi/db/do_backup.php
 * file: date('d-m-Y'). '@'. date('h.i.s') .'.sql';
 *
 */

$host = '127.0.0.1';
$user = 'username';
$pwd = 'salasana';
 
// Set object of backupmysql class
include 'backupmysql.class.php';

// Perform the backup for all databases
makeBackup($host, $user, $pwd, 'hotelli_customers');
makeBackup($host, $user, $pwd, 'hotelli_staff');
makeBackup($host, $user, $pwd, 'hotelli_reservations');
makeBackup($host, $user, $pwd, 'hotelli_rooms');

// Do backup
function makeBackup($h, $u, $p, $db) {

    $lang ='en';        // Indice of the "lang_...json" file with texts
    $dir ='backup/';    // Folder to store the ZIP archive with SQL backup

    $bk = new backupmysql($lang, $dir);

    // Data for connecting to MySQL
    $conn_data = ['host' => $h,
                  'user' => $u,
                  'pass' => $p,
                  'dbname' => $db];
   
    $bk->setMysql($conn_data);  // Set connection
    $tables = $bk->getTables(); // Get array with all the tables in database

    // If no error
    if($bk->error === false) {
        // If tables, creates the SQL backup of all the tables
        // and saves it in ZIP archive (get succesful or error message)
        $bk_sql = (count($tables) > 0) ? $bk->saveBkZip($tables) : 'No tables in database';

        // Use BR when print out to browser
        echo $bk_sql . "<br />";
    }
        else echo $bk->error;

    // Kill or Close PDO object
    $bk = null;
  
    return;
}
?>

Siitä vaan varmistamaan!

Ei kommentteja:

Lähetä kommentti