PHP代码执行.sql文件导入sql

网上找的办法都是通过分号(;)分割,这样的弊端是如果字段或者备注使用了该符号就无法导入

从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;


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值