· 6 years ago · Oct 15, 2019, 09:36 AM
1<?php
2/* BACKUP DEL DATABASE MYSQLi MACOS86.IT*/
3
4/* Report degli errori */
5error_reporting(E_ALL);
6
7/* Crea nuova istanza per la classe DatabaseBackup */
8$dbBackup = new DatabaseBackup();
9/* @Funzione chiamata - backupDatabase()
10 * @parametri - 1st Param - Default : recupera tutte le tabelle
11 Tabelle specifiche - array(table1,table2,table3...);
12 * 2nd Param - (Cartella) Se non specificata ne crea una dove lo script risiede
13 */
14$tables = '*';
15$dbBackup->backupDatabase($tables,'BackupLogs');
16
17class DatabaseBackup{
18 private $hostname = ''; /* DB Hostname */
19 private $username = ''; /* DB Username */
20 private $password = ''; /* DB Password */
21 private $database = ''; /* Database Name */
22 private $characterSet = 'utf8'; /* DB Character Set */
23 private $backupDirectory = 'BackupLogs'; /* Backup Directory */
24
25 /* Connessione a Mysqli */
26 private $link = '';
27
28 /* Classe del Constructor */
29 function __construct(){
30 /* Initializzazione delle variabili del DB */
31 $this->hostname = 'Nome del tuo host DB';
32 $this->username = 'nome utente DB';
33 $this->password = 'TI PIACEREBBE SAPERE LA PASSWORD';
34 $this->database = 'nome del tuo DB';
35 /* Funzione di chiamata all'inizializzazione del DB */
36 $this->initalizeDB();
37
38 }
39
40 /* Funzione per il collegamento a MySQL DB */
41 private function initalizeDB(){
42 $this->link = mysqli_connect($this->hostname, $this->username, $this->password, $this->database);
43 /* Messaggio se ci sono errori*/
44 if(mysqli_connect_error()){
45 die('Connection Error - '.mysqli_connect_errno().' : '.mysqli_connect_error());
46 }
47 /* Se non è definito un set caratteri imposta quello di default */
48 if(!mysqli_character_set_name($this->link)){
49 mysqli_set_charset($this->link,$this->characterSet);
50 }
51 }
52
53 /* Funzione di backup del Database */
54 public function backupDatabase($tables = '*',$backupDirectory = ''){
55 /* Se sono necessarie tutte le tabelle: */
56 if($tables == '*'){
57 $tables = array();
58 /* Recupera tutte le tabelle del database corrente */
59 $result = mysqli_query($this->link,"SHOW TABLES");
60 /* Passa attraverso tutte le righe e assegna l'array $tables */
61 while($row = mysqli_fetch_row($result)){
62 $tables[] = $row[0];
63 }
64 }else{
65 /* Se $tables è un array, assegnare direttamente altrimenti esplodere la stringa */
66 $tables = is_array($tables) ? $tables : explode(',',$tables);
67 }
68 /* Crea il database */
69 $sql = 'SET FOREIGN_KEY_CHECKS = 0;'."\n".'CREATE DATABASE IF NOT EXISTS `'.$this->database."`;\n";
70 /* Usa il database */
71 $sql .= 'USE `'.$this->database.'`;';
72
73 /* Passa attraverso tutti le $tables */
74 foreach($tables as $table){
75 /* Messaggio di output */
76 echo 'Salvataggio : `'.$table.'` : ';
77
78 /* Recupera i dettagli della tabella */
79 $tableDetails = mysqli_query($this->link, "SELECT * FROM ".$table);
80
81 /* Controlla il numero di colonne nella tabella */
82 $totalCols = mysqli_num_fields($tableDetails);
83
84 /* Se la tabella esiste, droppala */
85 $sql .= "\n\nDROP TABLE IF EXISTS `".$table."`;\n";
86 /* Crea la struttura dela tabella */
87 $result1 = mysqli_fetch_row(mysqli_query($this->link,'SHOW CREATE TABLE '.$table));
88 $sql .= $result1[1].";\n\n";
89
90
91 while($row = mysqli_fetch_row($tableDetails)){
92 $sql .= 'INSERT INTO `'.$table.'` VALUES(';
93 for($j=0; $j<$totalCols; $j++){
94 $row[$j] = preg_replace("/\n/","\\n",addslashes($row[$j]));
95 if (isset($row[$j]))
96 {
97 $sql .= '"'.$row[$j].'"' ;
98 }
99 else
100 {
101 $sql.= '""';
102 }
103
104 if ($j < ($totalCols-1))
105 {
106 $sql .= ', ';
107 }
108 }
109 $sql .= "); \n";
110 }
111 echo 'Completato <br/>';
112 }
113 $sql .= 'SET FOREIGN_KEY_CHECKS = 1;';
114 /* Se il secondo parametro non è stato specificato, verrà usato quello di default */
115 $backupDirectory = ($backupDirectory == '') ? $this->backupDirectory : $backupDirectory;
116 if($this->logDatabase($sql,$backupDirectory)){
117 echo '<h4>Database <span style="color:#7D0097">`'.$this->database.'`</span>esportato correttamente nella cartella - <span style="color:#1CAD7A"> `'.$backupDirectory.'`</span><h4>';exit;
118 }else{
119 echo '<h2>Errore esportazione database '.$this->database.'<h2>';exit;
120 }
121
122 }
123
124 /* Funzione di salvataggio del database */
125 private function logDatabase($sql,$backupDirectory = ''){
126 if(!$sql){
127 return false;
128 }
129
130 if(!file_exists($backupDirectory)){
131 if(mkdir($backupDirectory)){
132 $filename = 'log_'.$this->database.date('Y-m-d_H-i-s');
133 $fileHandler = fopen($backupDirectory.'/'.$filename.'.sql','w+');
134 fwrite($fileHandler,$sql);
135 fclose($fileHandler);
136 return true;
137 }
138 }else{
139 $filename = 'log_'.$this->database.date('Y-m-d_H-i-s');
140 $fileHandler = fopen($backupDirectory.'/'.$filename.'.sql','w+');
141 fwrite($fileHandler,$sql);
142 fclose($fileHandler);
143 return true;
144 }
145 return false;
146 }
147}