使用 php 将 .sql.gz 文件导入 mysql

importing an .sql.gz file into mysql using php

我目前正在编写一个脚本,只需单击 2 次即可轻松导入备份,但我找不到有关如何导入 .gz 文件的任何信息。 和 .sql 文件效果很好,但如果我要解压缩它,我也可以使用 phpmyadmin 导入它。

当我当前尝试导入 .gz 文件时,我遇到了一个不可读字符的巨大错误。

我怎样才能导入 .gz 文件

这里的重点是它是一个基于WEB的导入器

$userName = "root";
$password = "";
$dbName = "test";

    $conn = @new mysqli($serverName,$userName,$password,$dbName);

    if ($conn->connect_errno) {
    echo "Failed to connect to MySQL: " . $con->connect_errno;
    echo "<br/>Error: " . $con->connect_error;}
    

    $fileName = "189_dump.sql.gz";
    $temp = "";
    $lines = file($fileName);

    foreach($lines as $line){
        if(substr($line, 0, 2) == '--' || $line == '')
        continue;

        $temp .= $line;

        if(substr(trim($line), -1, 1) == ';'){
            $conn->query($temp) or print('Error performing query \'<strong>' . $temp . '\': '. '<br /><br />');
            $temp = "";
        }
    }
    echo "imported db (or not)";


?> 

我是这样修复的:

$lines = gzfile($fileName);

<?php

class reader{
    
    public $dbName;
    public $fileName;
    
    public function import($dbName, $fileName){
        $serverName = "localhost";
        $userName = "root";
        $password = "";

        $conn = new mysqli($serverName,$userName,$password,$dbName);

        $temp = "";
        $lines = gzfile($fileName);

        foreach($lines as $key => $line ){
            if(substr($line, 0, 2) == '--' || $line == '') continue;

            $temp .= $line;

            if(substr(trim($line), -1, 1) == ';'){
                $conn->query($temp) or print('Error performing query \'<strong>' . $temp . '\': '. '<br /><br />');
                $temp = "";}
        
        }
        echo "<script>alert('Database Imported')</script>";
    }
}
$bestand = new reader();
#               dbname  |  file name
$bestand->import("test", "testdb.sql.gz");

?>

如果您允许 system(),您可以:

<?php
system("gzip -dc < ".$file." | mysql -u $dbuser -p$dbpassword $dbname");