如何使用PHP将.sql文件导入到MySQL数据库中?

88

我正在尝试通过PHP代码导入一个 .sql 文件。但是,我的代码显示了以下错误:

There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:

MySQL Database Name:    test
MySQL User Name:    root
MySQL Password: NOTSHOWN
MySQL Host Name:    localhost
MySQL Import Filename:  dbbackupmember.sql

这是我的代码:

<?php
//ENTER THE RELEVANT INFO BELOW
$mysqlDatabaseName ='test';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='dbbackupmember.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;
exec($command,$output=array(),$worked);
switch($worked){
    case 0:
        echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>';
        break;
    case 1:
        echo 'There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:<br/><br/><table><tr><td>MySQL Database Name:</td><td><b>' .$mysqlDatabaseName .'</b></td></tr><tr><td>MySQL User Name:</td><td><b>' .$mysqlUserName .'</b></td></tr><tr><td>MySQL Password:</td><td><b>NOTSHOWN</b></td></tr><tr><td>MySQL Host Name:</td><td><b>' .$mysqlHostName .'</b></td></tr><tr><td>MySQL Import Filename:</td><td><b>' .$mysqlImportFilename .'</b></td></tr></table>';
        break;
}
?>

我做错了什么?SQL文件与当前目录相同。


2
你确定 dbbackupmember.sql 文件存在于与你的脚本相同的目录中吗?执行 var_dump( file_exists('dbbackupmember.sql') ); 会输出什么? - Amal Murali
是的,这是同一个目录,但我不知道为什么它显示错误。 - msalman
Apache 进程是否可以访问转储文件所存放的文件夹/文件?exec('whoami') 命令是否返回您的用户名?有时由于权限问题,Apache 进程也可能无法正确执行 exec 命令。 - Benno
可能是从PHP内部加载.sql文件的重复问题。 - T.Todua
2
这个回答解决了你的问题吗?如何使用MySQL命令行导入SQL文件? - Dharman
17个回答

0

另一种简单的方法是复制Adminer,然后导入SQL。


0

通过 PHP 代码帮助导入 SQL 文件数据

// sql file path
$filename = 'database_file_name.sql';

// Add this function into your helper file and add any where that you want to use
function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
    $connection = mysqli_connect($host,$uname,$pass) or die("Database Connection Failed");
    $selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected"); 
    
    $templine = '';
    $lines = file($filename); // Read entire file

    foreach ($lines as $line){
        // Skip it if it's a comment
        if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
            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) == ';')
            {
                mysqli_query($connection, $templine)
                or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
                $templine = '';
            }
        }
        echo "Tables imported successfully";
    }

// Calling import menthod
backup_tables('database_hostname','database_username','database_password','database_name');
// backup_tables function have 4paramater - database hostname, username, password and database name that you want import sql data.

如果你想从 PHP 脚本备份/导出数据库

// Call the backup_tables for export the database
backup_tables('hostname','UserName','pass','databses_name');
    
function backup_tables($host,$user,$pass,$name,$tables = '*'){
        $link = mysqli_connect($host,$user,$pass);
        if (mysqli_connect_errno()){
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        
        mysqli_select_db($link,$name);
        //get all of the tables
        if($tables == '*'){
            $tables = array();
            $result = mysqli_query($link,'SHOW TABLES');
            while($row = mysqli_fetch_row($result))
            {
                $tables[] = $row[0];
            }
        }else{
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }

        $return = '';
        foreach($tables as $table)
        {
            $result = mysqli_query($link,'SELECT * FROM '.$table);
            $num_fields = mysqli_num_fields($result);
            $row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
            $row2 = mysqli_fetch_row($row_query);
            $return.= "\n\n".$row2[1].";\n\n";

            for ($i = 0; $i < $num_fields; $i++) 
            {
                while($row = mysqli_fetch_row($result))
                {
                    $return.= 'INSERT INTO '.$table.' VALUES(';
                    for($j=0; $j < $num_fields; $j++) 
                    {
                        $row[$j] = addslashes($row[$j]);
                        $row[$j] = str_replace("\n", '\n', $row[$j]);
                        if (isset($row[$j])) { 
                            $return.= '"'.$row[$j].'"' ; 
                        } else { 
                            $return.= '""'; 
                        }
                        if ($j < ($num_fields-1)) { $return.= ','; }
                    }
                    $return.= ");\n";
                }
            }
            $return.="\n\n\n";
        }

        //save file
        $handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
        fwrite($handle,$return);
        fclose($handle);
    }

你的脚本有没有任何解释或说明它是如何工作的? - Tom

-1
function restoreDatabase($db_name,$file_path)
{

    //checking valid extension file
    $path_parts = pathinfo($file_path);
    $ext_file = $path_parts['extension'];
    $filename = $path_parts['basename'];

    if($ext_file == "sql")
    {
         $c = new Config();

         $confJson = $c->getConfig();
         $conf = json_decode($confJson);

         $dbhost   = "127.0.0.1";
         $dbuser   = $conf->db_username;  
         $dbpwd    = $conf->db_password;
         $dbname   = $db_name;   

         $dumpfile = $file_path;

         $is_file = file_exists($file_path);
         if($is_file == TRUE)
         {

             //passthru("/usr/bin/mysqldump --opt --host=$dbhost --user=$dbuser --password=$dbpwd $dbname < $dumpfile");

             //passthru("tail -1 $dumpfile");
             system('mysql --user='.$dbuser.' --password='.$dbpwd.' '.$db_name.' < '.$file_path);
             return "Database was restored from $filename ";

         }
         else 
         {
             return "Restore database was aborted due ".$filename." does not exist!";
         }


    }
    else
    {
        return "Invalid file format.Require sql file to restore this ".$db_name." database. ".$filename." is not sql file format\n(eg. mybackupfile.sql).";
    }
}

-1
众所周知,MySQL在PHP 5.5.0中已被弃用,并在PHP 7.0.0中被移除ref,因此我已将接受的answer转换为mysqli。
<?php
// Name of the file
$filename = 'db.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '123456';
// Database name
$mysql_database = 'mydb';

$connection = mysqli_connect($mysql_host,$mysql_username,$mysql_password,$mysql_database) or die(mysqli_error($connection));

// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines 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
    mysqli_query($connection,$templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}
 echo "Tables imported successfully";
?>

这是值得赞扬的,但实际上这是一种可怕的方法。我不推荐并且必须反对。使用MySQL备份功能或multi_query(小心)代替。 - Dharman

-2

我觉得你可以尝试这段代码,它对我的情况有效:

<?php

$con = mysqli_connect('localhost', 'root', 'NOTSHOWN', 'test');

$filename = 'dbbackupmember.sql';
$handle = fopen($filename, 'r+');
$contents = fread($handle, filesize($filename));

$sql = explode(";", $contents);
foreach ($sql as $query) {
 $result = mysqli_query($con, $query);
 if ($result) {
  echo "<tr><td><br></td></tr>";
  echo "<tr><td>".$query."</td></tr>";
  echo "<tr><td><br></td></tr>";
 }
}

fclose($handle);
echo "success";


?>


如果任何一个值包含;,那么这个程序就无法工作。 - Nico Haase

-2

我使用这段代码并成功运行:

$filename = 'apptoko-2016-12-23.sql'; //change to ur .sql file
                            $handle = fopen($filename, "r+");
                            $contents = fread($handle, filesize($filename));

                            $sql = explode(";",$contents);// 
                            foreach($sql as $query){
                                $result=mysql_query($query);
                                if ($result){
                                 echo '<tr><td><BR></td></tr>';
                                 echo '<tr><td>' . $query . ' <b>SUCCESS</b></td></tr>';
                                 echo '<tr><td><BR></td></tr>';
                                }
                            }
                            fclose($handle);

如果任何一个值包含 ;,这将无法工作。 - Nico Haase

-2

解决特殊字符问题

 $link=mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());

//charset important
mysql_set_charset('utf8',$link);

请在您的答案中添加一些解释,以便其他人可以从中学习。就我所见,该代码没有从任何转储中读取,也没有插入任何内容。 - Nico Haase

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接