Форум программистов, компьютерный форум, киберфорум
PHP: базы данных
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.91/11: Рейтинг темы: голосов - 11, средняя оценка - 4.91
0 / 0 / 0
Регистрация: 24.06.2017
Сообщений: 5

Как загрузить БД из phpmyadmin в папку сайта?

26.06.2017, 21:03. Показов 2172. Ответов 2

Студворк — интернет-сервис помощи студентам
Необходимо загрузить БД из phpmyadmin в папку сайта, чтобы можно было кинуть на любой другой сервер и содержимое таблиц было все то же. Как правильно это сделать?
0
Лучшие ответы (1)
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
26.06.2017, 21:03
Ответы с готовыми решениями:

Как загрузить на сервер phpmyadmin БД больше 2,048 КБ?
Загружаю бд на сервак phpmyadmin. А там надпись: Максимальный размер: 2,048 КБ. А если у меня бд больше 2,048 КБ тогда как загружать?? ...

как загрузить большой дамп через phpmyadmin?
всем привет! нужно загрузить дамп размером пару гигов на свой локальный сервер. нашёл вот такой способ: Попробуйте создать в корне...

Как загрузить файл в папку assets?
file = new File("/assets/","sagittarius.xml"); При запуске зависает на прогрес-баре. Помогите разобраться package ru.load.file; ...

2
313 / 312 / 221
Регистрация: 11.07.2015
Сообщений: 1,107
26.06.2017, 21:10
Лучший ответ Сообщение было отмечено Liloo как решение

Решение

PHP
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';
0
Эксперт PHP
4925 / 3920 / 1620
Регистрация: 24.04.2014
Сообщений: 11,441
27.06.2017, 00:01
Code
1
mysqldump -u USER -pPASSWORD DATABASE > /path/to/file/dump.sql
Если из phpmyadmin, то там есть вкладка Export
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
27.06.2017, 00:01
Помогаю со студенческими работами здесь

Как загрузить папку с файлами на ftp сервер
Здравствуйте. Всех с НГ!) есть вопрос: Как загрузить папку с файлами на ftp сервер посредством vb.net ?

Как загрузить файл в определенную папку на сервере
Здравствуйте, Возможно ли когда конвертируешь .rpt файл в .pdf, чтобы когда нажать на кнопку &quot;Конвертировать&quot; оно сохранила...

Как загрузить видео на ютуб с другого сайта? (Загрузить видео в конкретный плейлист)
Как загрузить, с другого сайта, видео на ютуб в конкретный плейлист? А то после того как они прекратили поддержку YouTube API v2 ...

Как загрузить файл не именно в папку uploads, а в разные папки
Как загрузить файл не именно в папку uploads,а в разные папки.То есть не просто поменять значение $uploaddir,а именно изменить его в...

Как загрузить файл в определённую папку при нажатии на кнопку?
Как мне сделать загрузку файлов в определённую папку при нажатии на кнопку? И где это можно сделать в C++ или в C#?


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь постоянного тока с R, L, C, k(ключ), U, E, J. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа, решает её и находит переходные токи и напряжения на элементах схемы. . . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru