Loading .sql files from within PHP

Josh Smeaton picture Josh Smeaton · Sep 29, 2008 · Viewed 136.9k times · Source

I'm creating an installation script for an application that I'm developing and need to create databases dynamically from within PHP. I've got it to create the database but now I need to load in several .sql files. I had planned to open the file and mysql_query it a line at a time - until I looked at the schema files and realised they aren't just one query per line.

So, how do I load an sql file from within PHP (as phpMyAdmin does with its import command)?

Answer

Luis Granja picture Luis Granja · Aug 24, 2011
$db = new PDO($dsn, $user, $password);

$sql = file_get_contents('file.sql');

$qr = $db->exec($sql);