如何使用php函数导入.sql文件

时间:2018-04-12 11:02:05

标签: php mysql database xampp

我正在使用Xampp,我正在尝试将表导入我的数据库,但它总是返回案例1.我不知道为什么它不起作用。这是我的代码:

$mysqlDatabaseName ='postcodes';
$mysqlUserName ='root';
$mysqlPassword ='';
$mysqlHostName ='localhost';
$mysqlImportFilename ='http://localhost/import_tbl/postcode_withLatlang.sql';

$command='mysql -h' .$mysqlHostName .' -u' .$mysqlUserName .' -p' .$mysqlPassword .' ' .$mysqlDatabaseName .' < ' .$mysqlImportFilename;

//var_dump( file_exists('postcode_withLatlang.sql') );

$output = array();

 exec($command, $output, $worked);
print_r($output);
echo $worked;

// test whether they are imported successfully or not
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;
 }

请帮帮我

2 个答案:

答案 0 :(得分:0)

您需要将$mysqlImportFilename ='http://localhost/import_tbl/postcode_withLatlang.sql';更改为$mysqlImportFilename ='postcode_withLatlang.sql';,然后将您的php脚本文件放在带有.sql文件的文件夹中,并从该文件夹运行它。

答案 1 :(得分:0)

现在正在运作! 首先,它在本地服务器中不起作用,其次,我使用 system()函数代替 exec()函数,最后,它在我的数据库中生成一个表。谢谢大家!