开发者

Import mysql dump using php

开发者 https://www.devze.com 2023-02-20 04:52 出处:网络
I have mysql 开发者_开发知识库dump file. How I can import this file into mysql using php?Depends on how big the dump file is, really. A small one can just be added with a sql command. A larger one can

I have mysql 开发者_开发知识库dump file. How I can import this file into mysql using php?


Depends on how big the dump file is, really. A small one can just be added with a sql command. A larger one can be imported with a script.

A quick search will reveal many pre-made scripts that break down a dump into smaller chunks in order to not overload the server. I have used this one in the past: http://www.ozerov.de/bigdump.php


You dump is probably a file that just contains a lot of SQL queries.

The simplest way to import such a dump is to use the mysql command-line client (especially if the file is big !) :

mysql --user=USERNAME --password=PASSWORD --host=HOST DB_NAME < /path/to/your/file.sql


If you can connect to your server with some command-line access (typically, using ssh), that's the way to go.

Else, I suppose you could execute such a command with system()


I you want to use PHP, you can easily use the file() function, which reads a file into an array line by line.

You could try something like that:

mysql_connect(BD_HOST, DB_USER, BD_PASS) or die("Error connecting to MySQL server: ".mysql_error());
mysql_select_db(DB_NAME);

$all_lines = file("mysql_dump.sql", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);

foreach($all_lines as $query) {
    if(substr($query, 0, 2) == "--") {
        continue;
    }

    mysql_query($query) or die("Error executing query <br/>&nbsp;&nbsp;"$query\"<br/>".mysql_error());
}


U can use multi_query, to import database dump files of medium file-size.

$command = file_get_contents($dumpfile);
$conn->multi_query($command);
while (mysqli_next_result($conn)); // Flush out the results.

Note: The exact file-size limit would be dependent on your server configuration eg. max_allowed_packet etc.

0

精彩评论

暂无评论...
验证码 换一张
取 消