MySQL导入成功通过PhpMyAdmin导入转储文件。但是通过PHP导入不起作用

时间:2014-06-16 12:19:29

标签: php mysql phpmyadmin

好的,我已经拉了好几天头发并且无法知道发生了什么。我可以通过phpmyadmin成功导入mysql转储文件,但每当我尝试使用任何PHP脚本将其导入数据库时​​,都会给我错误。目前,我正在使用此脚本。

<?php

$mysqlDatabaseName = 'dbnname';
$mysqlUserName = 'username';
$mysqlPassword = 'password';
$mysqlHostName = 'localhost';
$mysqlImportFilename = dirname(__FILE__) . '/database.sql';
//DONT EDIT BELOW THIS LINE
//Export the database and output the status to the page
$con = mysqli_connect($mysqlHostName, $mysqlUserName, $mysqlPassword, $mysqlDatabaseName);
if (!$con) {
    die('connection failed');
}
$command = 'mysql -h' . $mysqlHostName . ' -u' . $mysqlUserName . ' -p' . $mysqlPassword . ' ' . $mysqlDatabaseName . ' < ' . $mysqlImportFilename;
$result = mysqli_query($con, $command);
if ($result) {
    print_r('True $result: ' . $result);
} else {
    print_r('False $result: ' . $result . mysqli_errno($con));
} // TODO need to print mysqli_errno

使用脚本时遇到错误: -

False $result: 1064

通过phpmyadmin手动导入时没有错误。

由于

2 个答案:

答案 0 :(得分:2)

你要向mysqli提供的$command是对独立mysql命令行界面的调用而不是mysqli函数调用。使用PHP系统()或类似函数调用外部mysql CLI。

答案 1 :(得分:0)

试试这个

<?php

// Name of the file
$filename = 'database.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'root';
// MySQL password
$mysql_password = '';
// Database name
$mysql_database = 'dbnname';

// 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";
?>

祝你好运