How to import sql file using PHP

I have a .sql file and I want to use PHP to import this into a database. Does anyone know how?

For example:

if (isset($_POST[‘import’])){
//read the .sql file and import into a db

}

You can use exec() function .
exec(‘mysql -u username -p password --database databasename < locationofsqlfile’);

locationofsqlfile must be server side absolute file path.

After you do all the usual PHP connection stuff, run a query like
LOAD DATA INFILE ‘[the .sql file]’ INTO TABLE [whatever]

I tried this:

exec(‘mysql -u ‘.$mysql_username.’ -p ‘.$mysql_password.’ --database ‘.$mysql_database.’ < db.sql’);

but it didnt work

You really should be using Mittineague’s method, if you are unsure how apply the method with PHP just post back.

mittineague’s method will not work if it is actually an SQL file

in other words, if the contents of the file are SQL statements (which is what you get when you export a database using the mysqldump utility) then you have to execute the file, not load it

why would you want to do this with php?

you need the absolute path of db.sql. Also the exec function might be disabled if you are on shared hosting.

You could do something like this instead:


$dbconn = mysql_connect('localhost','user','password');
mysql_select_db('db_name',$dbconn);

$file = '/path/to/import.sql';

if($fp = file_get_contents($file)) {
  $var_array = explode(';',$fp);
  foreach($var_array as $value) {
    mysql_query($value.';',$dbconn);
  }
}

Untested but should work.