Today to introduce you, how to use PHP automatic execution. sql file. In fact, it is very simple to get the contents of the SQL file and then execute each sentence of SQL statement at once.
This is the code
//Read File contents$_sql=file_get_contents(' Test.sql '); $_arr=Explode(‘;‘,$_sql);$_mysqli=NewMysqli (Db_host,db_user,db_pass);if(Mysqli_connect_errno()) { Exit(' Error connecting database ');}//Execute SQL statementforeach($_arr as $_value) { $_mysqli->query ($_value.‘;‘);}$_mysqli-close ();$_mysqli=NULL;
Above text.sql is the SQL file you need to execute, db_host hostname, db_user username, db_pass password!
This is just the most basic automated SQL file, you can also customize the name of the build database by deleting the following code in the SQL file
12 |
CREATE DATABASE IF not EXISTS DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci; Use database name |
Then add the code before executing all the SQL statements in text.php
$_mysqli->query ("CREATE database IF not EXISTS name DEFAULT CHARACTER SET UTF8 COLLATE utf8_general_ci;") ); $_mysqli->query ("Use database name");
Replace the database name with the name you need to modify! More features you can explore by yourself!
Reprint Please specify source: http://www.ly89.cn/detailB/35.html
Using PHP to execute SQL files, import SQL files into the database