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