【问题标题】:importing an .sql.gz file into mysql using php使用 php 将 .sql.gz 文件导入 mysql
【发布时间】:2020-08-27 09:18:54
【问题描述】:

我目前正在编写一个脚本,该脚本只需单击 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)";


?> 

【问题讨论】:

  • 显然你应该在逐行读取文件之前执行decompression
  • 我明白这一点,但我找不到任何有用的信息来说明如何在我的代码中包含和使用它,减压很有趣,但如果我不能适应它或使它无用的话.
  • $unzipped = gzdecode(file_get_contents("189_dump.sql.gz"));
  • 仍然是同样的问题,我只是找不到任何关于如何将解压文件包含到我的代码中的信息。这就是我问的问题
  • 您可能应该只使用shell_exec() 压缩并通过管道连接到 mysql 客户端。不要试图复制在 PHP 中运行 SQL 脚本的能力。请参阅我对stackoverflow.com/a/4028289/20860的回答

标签: php mysql import gzip


【解决方案1】:

这就是我修复它的方法:

$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");

?>

【讨论】:

    【解决方案2】:

    如果你有 system() 允许,你可以:

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

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多