Running MySQL *.sql files in PHP
This question comes up from time to time. There's no good solution for running a .sql script directly from PHP. There are edge cases where statements common in a .sql script can't be executed as SQL statements. For example, the mysql tool has builtin commands that are not recognized by the MySQL Server, e.g. CONNECT
, TEE
, STATUS
, and DELIMITER
.
So I give +1 to @Ignacio Vazquez-Abrams's answer. You should run your .sql script in PHP by invoking the mysql
tool, for instance with shell_exec()
.
I got this test working:
$command = "mysql --user={$vals['db_user']} --password='{$vals['db_pass']}' "
. "-h {$vals['db_host']} -D {$vals['db_name']} < {$script_path}";
$output = shell_exec($command . '/shellexec.sql');
See also my answers to these related questions:
- Loading .sql files from within PHP
- is it possible to call a sql script from a stored procedure in another sql script?
- PHP: multiple SQL queries in one mysql_query statement
$commands = file_get_contents($location);
$this->_connection->multi_query($commands);
You'll need to create a full SQL parser for this. I recommend you use the mysql
command line tool for this instead, invoking it externally from PHP.