Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a *.sql file using php

Tags:

php

mysql

I need to execute a .sql file which has about 48 tables to create. It is consisting of comments and sql commands which are ending in a ";". Is there a way to run these sql commands taking them to a single string and at once. I mean I need to run the whole file at once using php. I can execute that file line by line using mysql_query function. But I need to do is to execute all of them at once as same as in phpmyadmin.

Is there a way to do it. I need to do this using php. Can anyone help me please?

like image 928
chinthakarukshan Avatar asked Feb 24 '23 07:02

chinthakarukshan


2 Answers

You can explode your queries

function batch($file){
    $queries = explode(";", $file);
    foreach($queries as $query){
        mysql_query($query);
    }
}
like image 27
genesis Avatar answered Mar 02 '23 00:03

genesis


You are looking for

  • mysqli_multi_query - Executes one or multiple queries which are concatenated by a semicolon.

An alternative would be to use the command line client:

mysql -u USERNAME -p DATABASENAME < FILE.SQL 

You can probably use that with exec and/or system, but then you have to provide the password after -p. The above command will prompt you for it.

like image 63
Gordon Avatar answered Mar 02 '23 00:03

Gordon