使用php将sql文件导入到远程mysql数据库中


Importing a sql file into a remote mysql db with php

php和mysql新手,我正在尝试将导出的sql文件插入到远程数据库中。我正在从1和1尝试此代码,但它不起作用。

$create_install_db_server = 'testdb.example.com';
$create_install_db_username = 'test123';
$create_install_db_password = 'test789';
$create_install_db_name = 'test';
$sqlfile = '/home/path/to/localsql.sql';
$command='mysql -h' . $create_install_db_server .' -u' . $create_install_db_username .' -p' . $create_install_db_password .' ' . $create_install_db_name .' < ' . $sqlfile;
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.';
        break;
}

@srikanth,我有另一种方法可以做到这一点,试试这个

<?php
// Name of the file
$filename = 'churc.sql';
// MySQL host
$mysql_host = 'testdb.example.com';
// MySQL username
$mysql_username = 'test123';
// MySQL password
$mysql_password = 'test789';
// Database name
$mysql_database = 'Test';
// Connect to MySQL server
mysql_connect($mysql_host, $mysql_username, $mysql_password) or die('Error connecting to MySQL server: ' . mysql_error());
// Select database
mysql_select_db($mysql_database) or die('Error selecting MySQL database: ' . mysql_error());
// 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
    mysql_query($templine) or print('Error performing query ''<strong>' . $templine . ''': ' . mysql_error() . '<br /><br />');
    // Reset temp variable to empty
    $templine = '';
}
}
 echo "Tables imported successfully";
?>

希望这对你有所帮助。:)

注意:不赞成使用mysql,相反,您可以使用Mysqli,PDO,如下所示。

$db = new PDO($mysql_host, $mysql_username, $mysql_password);
$sql = file_get_contents('churc.sql');
$qr = $db->exec($sql);

对于执行大型sql文件,我上面的答案是不够的,所以我建议你看看@Abu sadat这里的答案

尝试以下方法

  • 在尝试执行之前,对命令进行回显

  • 尝试在终端上运行命令-检查是否成功

  • 如果成功,请用一个简单的命令(如"touch/tmp/abc.txt")替换exec,并检查是否正在创建文件。

通过这样做,您试图找出mysql命令是否有问题,或者php 中的exec函数是否有问题