Search code examples
phpmysqldatabasexampp

how to import a .sql file using php function


I am using Xampp server and I am trying to import a table into my database which is not working. here is my code:

$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;
 }

please help me


Solution

  • It's working now! Firstly, it didn't work in local server and secondly, instead of exec() function I used the system() function and finally, it generates a table in my database. Thanks everyone!