网上找的办法都是通过分号(;)分割,这样的弊端是如果字段或者备注使用了该符号就无法导入
从google搜了老外的办法原文链接:How do I import a .sql file in mysql database using PHP? - Stack Overflow
下面是我使用了他的代码导入的源码
//将表导入数据库
$_sql = file($file);;//写自己的.sql文件
//第一个参数为域名,第二个为用户名,第三个为密码,第四个为数据库名字
$_mysqli = new mysqli($name, $root, $pwd, $database);
if (mysqli_connect_errno()) {
exit('连接数据库出错' . PHP_EOL);
} else {
// Temporary variable, used to store current query
$tempLine = '';
//执行sql语句
foreach ($_sql as $line) {
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$tempLine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';') {
// Perform the query
$query_res = $_mysqli->query($tempLine . ';');
if (!$query_res) {
echo "↓=================================导入sql语句失败=================================" . PHP_EOL;
echo ($tempLine) . PHP_EOL;
echo '错误:' . $_mysqli->error . PHP_EOL;
echo "↑=================================导入sql语句失败=================================" . PHP_EOL;
echo "-----------------------------------------------------------------------------------" . PHP_EOL;
}
// Reset temp variable to empty
$tempLine = '';
}
}
echo "导入数据库执行完成" . PHP_EOL;
}
$_mysqli->close();
$_mysqli = null;