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)?
An updated solution of Plahcinski solution. Alternatively you can use fopen and fread for bigger files:
The easiest and fastest way to load & parse phpmyadmin dump or mysql dump file..
I noticed that the PostgreSQL PDO driver does not allow you to run scripts separated by semicolons. In order to run a .sql file on any database using PDO it is necessary to split the statements in PHP code yourself. Here is a solution that seems to work quite well:
https://github.com/diontruter/migrate/blob/master/src/Diontruter/Migrate/SqlScriptParser.php
The referenced class has done the trick for me in a database independent way, please message me if there are any issues. Here is how you could use the script after adding it to your project:
Works on Navicat dumps. Might need to dump the first /* */ comment navicat puts in.
Try This:
Just to restate the problem for everyone:
PHP's mysql_query, automatically end-delimits each SQL commands, and additionally is very vague about doing so in its manual. Everything beyond one command will yield an error.
On the other mysql_query is fine with a string containing SQL-style comments, \n, \r..
The limitation of mysql_query reveals itself in that the SQL parser reports the problem to be directly at the next command e.g.
Here is a quick solution: (assuming well formatted SQL;