Today I have found the following question, because of a new answer added, which was just a rewrite of the accepted answer but using a newer API.
How do I import a .sql file in mysql database using PHP?
I tested the code from the question and it worked perfectly fine for me when I specified the absolute path. (Unless the file is in the directory from which you call the script). If as OP claims in the comments, the file is where it is supposed to be then the issue becomes unreproducible. Normally I would vote to close as off-topic and delete the question unless OP comes back with more information. However, this is an old question and OP accepted some questionable workaround. On top of this, the question gathered 26 answers over the last 7 years. Most of them low quality.
If we were to ignore the non-existent issue in the question and we were to treat this as a canonical for this common problem then the solution, which OP has in the question is the most correct one in my opinion. There are two more answers (this and this) proposing the same solution, just with different syntax.
If for some reason you have no access to the command line from PHP script, then the workaround would be to use multi_query
function from mysqli or exec()
from PDO. However, both of these approaches can only execute multiple queries concatenated by ;
and they can't import an SQL file!
The worst solution, in my opinion, would be to write an SQL parser in PHP. Certainly splitting on ;
is not a foolproof scenario.
There are other almost identical questions with similar answers:
Loading .sql files from within PHP
how to import a .sql file using php function
What should we do with this question? (and the other 2 I have linked too, to a lesser extent). Should we close as lacking MCVE and then delete? Should we close as duplicate? Should we leave it alone as suggested to me in SOCVR?