简体   繁体   中英

MySQL Import Successfully Imports Dump File Via PhpMyAdmin. But Importing Through PHP Doesn't Work

Ok, I've been pulling my hairs for few days and can't find out what's happening. I can successfully import mysql dump file through phpmyadmin but whenever I try to import it into the database using any php script it, gives me error. Currently, I'm using this script.

<?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

Error I'm getting when using script:-

False $result: 1064

There is no error while manually importing through phpmyadmin.

Thanks

The $command which you are feeding to mysqli is the call for the standalone mysql command line interface and not a mysqli function call. Use the PHP system() or similar functions to call the external mysql CLI.

Try this

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

Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM