1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
| <?php
// параметры базы данных
define("MHOST", "localhost");
define("MUSER", "имя пользователя базы данных");
define("MPASS", "пароль пользователя базы данных");
define("MDBNM", "имя базы данных mysql");
// файл экспорта
$backupfile = dirname(__FILE__) . '/data/export.sql';
// кодировка структуры
$serverCs = "utf8";
// кодировка данных
$dannyeCs = "utf8";
// пишем в строку
$out = "";
// сохранять структуру и данные
$data = 1;
// комментарии
$comment = '';
// исключяя таблицы
$except_tables = array();
// исключяя содержимое таблиц
$except_tables_data = array('user');
ignore_user_abort(true);
chdir(dirname(__FILE__).'');
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(3600);
ini_set('max_execution_time',3600);
// соединяемся с БД
$mysqli = new mysqli(MHOST, MUSER, MPASS, MDBNM);
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
unlink($backupfile);
// форматируем
$CONF['date'] = '%d.%m.%Y %H:%M Uhr';
// лимиты
$mem_limit = 10;
$max_size = 500000 * $mem_limit;
// имена переменных и констант
$time = time();
// начало
// create comment
$out.= "# MySQL дамп базы данных\n";
$out.= "# backup date and time: " . strftime($CONF['date'], $time) . "\n";
$out.= "# built by mysql_backup 0.1\n";
// write users comment
if ($comment)
{
$out.= "# comment:\n";
$comment = preg_replace("'\n'", "\n# ", "# " . $comment);
foreach(explode("\n", $comment) as $line) $out.= $line . "\n";
$out.= "\n";
}
$mysqli->set_charset($serverCs);
$out.= "set names " . $serverCs . ";\n\n";
$out.= "### Текущий набор символов: ".$mysqli->character_set_name() . " ###\n";
// get tables and views
$all_tables = $all_views = array();
$res = $mysqli->query("show table status");
while ($row = $res->fetch_array())
{
if (sizeof($row['Engine']) == 0)
{
$all_views[] = $row;
}
else
{
$all_tables[] = $row;
}
}
// get table structures
$all_tables_new = array();
foreach($all_tables as $key => $table)
{
if (!in_array($table['Name'], $except_tables))
{
$res1 = $mysqli->query("SHOW CREATE TABLE `" . $table['Name'] . "`");
$tmp = $res1->fetch_array();
$table_sql[$table['Name']] = $tmp["Create Table"];
$all_tables_new[$key] = $table;
}
}
$all_tables = $all_tables_new;
unset($all_tables_new);
// find foreign keys
$fks = array();
if (isset($table_sql))
{
foreach($table_sql as $tablenme => $table)
{
$tmp_table = $table;
// save all tables, needed for creating this table in $fks
while (($ref_pos = strpos($tmp_table, " REFERENCES ")) > 0)
{
$tmp_table = substr($tmp_table, $ref_pos + 12);
$ref_pos = strpos($tmp_table, "(");
// cut of '`' at the begining and end of fk-name
$fks[$tablenme][] = trim(str_replace('`', '', substr($tmp_table, 0, $ref_pos)));
}
}
}
// order $all_tables and check for ring constraints
$all_tables_copy = $all_tables;
// orders the tables in $tables according to the constraints in $fks
// $fks musst be filled like this: $fks[tablename][0]=needed_table1; $fks[tablename][1]=needed_table2; ...
function order_sql_tables($tables, $fks)
{
// do not order if no contraints exist
if (!count($fks)) return $tables;
// order
$new_tables = array();
$existing = array();
$modified = TRUE;
while (count($tables) && $modified == TRUE)
{
$modified = FALSE;
foreach($tables as $key => $row)
{
// delete from $tables and add to $new_tables
// does table has fk?
if (isset($fks[$row['Name']]))
{
// find required tables
foreach($fks[$row['Name']] as $needed)
{
// go to next table if not all needed tables exist in $existing
// in order to find all tables first, which do have no constraints or constraints which can already be resolved
if (!in_array($needed, $existing))
{
continue2;
}
}
}
// if all required tables are already in the new-tables-list:
// delete from $tables and add to $new_tables
$existing[] = $row['Name'];
$new_tables[] = $row;
prev($tables);
unset($tables[$key]);
$modified = TRUE;
}
}
if (count($tables))
{
// probably there are 'circles' in the constraints, because of that no proper backups can be created
// This will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables.
// Until now I just add the lasting tables to $new_tables, return them and print a warning
foreach($tables as $row) $new_tables[] = $row;
return false;
}
return $new_tables;
}
$all_tables = order_sql_tables($all_tables, $fks);
$ring_constraints = false;
// ring constraints found
if ($all_tables === false)
{
$ring_constraints = true;
$all_tables = $all_tables_copy;
$out.= "\n# ring constraints workaround\n";
$out.= "SET FOREIGN_KEY_CHECKS=0;\n";
$out.= "SET AUTOCOMMIT=0;\n";
$out.= "START TRANSACTION;\n";
}
unset($all_tables_copy);
$out.= "\n### drop all tables first ###\n";
foreach(array_reverse($all_tables) as $row)
{
$out.= "\nDROP TABLE IF EXISTS `" . $row['Name'] . "`;";
}
$out.= "\n";
foreach($all_tables as $row)
{
$tablename = $row['Name'];
$auto_incr[$tablename] = $row['Auto_increment'];
$out.= "\n\n";
// export tables
$out.= "### structure of table `" . $tablename . "` ###\n\n";
$out.= $table_sql[$tablename];
// add auto_increment value
if ($auto_incr[$tablename])
{
$out.= " AUTO_INCREMENT=" . $auto_incr[$tablename];
}
$out.= ";";
$out.= "\n\n\n";
// if saving is successful, then empty $out, else set error flag
if (strlen($out) > $max_size)
{
if ($out = file_put_contents($backupfile, $out, FILE_APPEND)) $out = "";
else die('writing file');
}
}
$mysqli->close();
// соединяемся с БД
$mysqli = new mysqli(MHOST, MUSER, MPASS, MDBNM);
if ($mysqli->connect_errno) {
die('Connect Error: ' . $mysqli->connect_errno);
}
$mysqli->set_charset($dannyeCs);
$out.= "set names " . $dannyeCs . ";\n\n";
$out.= "### Текущий набор символов: ".$mysqli->character_set_name() . " ###\n";
if ($data)
foreach($all_tables as $row) if (!in_array($row['Name'],$except_tables_data))
{
$tablename = $row['Name'];
$auto_incr[$tablename] = $row['Auto_increment'];
$out.= "\n\n";
// export data
$out.= "### data of table `" . $tablename . "` ###\n\n";
// check if field types are NULL or NOT NULL
$res3 = $mysqli->query("show columns from `" . $tablename . "`");
$res2 = $mysqli->query("select * from `" . $tablename . "`");
if (!$res2)
{
die('MySQL error: ' . $mysqli->error);
}
$number_of_rows = $res2->num_rows;
if ($number_of_rows > 0)
{
for ($j = 0; $j < $number_of_rows; $j++)
{
$out.= "insert into `" . $tablename . "` values (";
$row2 = $res2->fetch_row();
// run through each field
for ($k = 0; $k < $nf = $res2->field_count; $k++)
{
// identify null values and save them as null instead of ''
if (is_null($row2[$k])) $out.= "null";
else $out.= "'" . $mysqli->real_escape_string($row2[$k]) . "'";
if ($k < ($nf - 1)) $out.= ", ";
}
$out.= ");\n";
// if saving is successful, then empty $out, else set error flag
if (strlen($out) > $max_size)
{
if ($out = file_put_contents($backupfile, $out, FILE_APPEND)) $out = "";
else die('writing file');
}
}
}
else
{
$out.= "-- table is empty\n"; // no data
}
// if saving is successful, then empty $out, else set error flag
if (strlen($out) > $max_size)
{
if ($out = file_put_contents($backupfile, $out, FILE_APPEND)) $out = "";
else die('writing file');
}
}
// views
// get all view definitions
$all_views_definitions = array();
foreach($all_views as $row)
{
$viewname = $row['Name'];
if (!in_array($viewname, $except_tables))
{
$res4 = $mysqli->query("show create view `" . $viewname . "`");
if (!$res4)
{
die("MySQL error: " . $mysqli->error);
}
$row4 = $res4->fetch_array();
$all_views_definitions[$viewname] = $row4['Create View'];
}
}
if (sizeof($all_views_definitions) > 0) $out.= "\n\n### views ###\n\n";
// order $all_views and check for ring constraints
// orders the views in $views according to the constraints in $fks
function order_sql_views($views)
{
// order
$new_views = array();
$existing = array();
$modified = TRUE;
while (count($views) && $modified == TRUE)
{
$modified = FALSE;
foreach($views as $name => $definition)
{
// delete from $views and add to $new_views
// does view refer to another view
foreach(array_keys($views) as $dependendName)
{
if ($name != $dependendName && stripos($definition, '`' . $dependendName . '`') !== false)
{
continue2;
}
}
// if all required views are already in the new-views-list:
// delete from $views and add to $new_views
$new_views[$name] = $definition;
prev($views);
unset($views[$name]);
$modified = TRUE;
}
}
if (count($views))
{
// probably there are 'circles' in the constraints, because of that no proper backups can be created
// This will be fixed sometime later through using 'alter table' commands to add the constraints after generating the tables.
// Until now I just add the lasting tables to $new_tables, return them and print a warning
foreach($views as $name => $definition) $new_views[$name] = $definition;
return false;
}
return $new_views;
}
$all_views_definitions_copy = $all_views_definitions;
$all_views_definitions = order_sql_views($all_views_definitions);
$ring_constraints = false;
// ring constraints found
if ($all_views_definitions === false)
{
$all_views_definitions = $all_views_definitions_copy;
// if not already written because of tabel ring constraints
if (!$ring_constraints)
{
$out.= "\n# ring constraints workaround\n";
$out.= "SET FOREIGN_KEY_CHECKS=0;\n";
$out.= "SET AUTOCOMMIT=0;\n";
$out.= "START TRANSACTION;\n";
}
$ring_constraints = true;
}
unset($all_views_definitions_copy);
// view drop statements (in reverse order)
if (count($all_views_definitions) > 0)
{
$out.= "### drop all views first ###\n\n";
foreach(array_reverse($all_views_definitions) as $view_name => $view_definition)
{
$out.= "DROP VIEW IF EXISTS `" . $view_name . "`;\n";
}
$out.= "\n\n";
}
// view definitions
foreach($all_views_definitions as $view_name => $view_definition)
{
$out.= "### create statement of view `" . $view_name . "` ###\n\n";
$out.= $view_definition;
$out.= ";\n\n";
}
// if saving is successful, then empty $out, else set error flag
if (strlen($out) > $max_size)
{
if ($out = file_put_contents($backupfile, $out, FILE_APPEND)) $out = "";
else die('writing file');
}
// if db contained ring constraints
if ($ring_constraints)
{
$out.= "\n\n# ring constraints workaround\n";
$out.= "SET FOREIGN_KEY_CHECKS=1;\n";
$out.= "COMMIT;\n";
}
// save to file
if (!file_put_contents($backupfile, $out, FILE_APPEND)) die('writing file');
if (!file_exists($backupfile)) die ('error checking file, maybe chmod 777 on this dir');
echo 'ok'; |