This article describes how to execute mysql statements in batches in PHP. examples are given in this article. If you want to connect multiple mysql statements, for example
$ Sqls = "insert table a values (1, 2); insert table a values (2, 3 );"
You can use three methods in php to execute the command:
Mysql_query
Pdo
Mysqli
Three methods are available when sqls statements are no problem.
However
An error occurs when an SQL statement is incorrect.
The first SQL error: false is returned for all three methods.
The first SQL statement is correct, and the second SQL statement is incorrect: mysql_query, pdo, and mysqli: query. true is also returned. SoAt this time, you cannot determine whether your sqls has that statement.
There are several ways to solve this problem:
1. parse SQL statements
Split each SQL statement and run it. In this way, each statement is executed separately. However, this method has several more methods, so it is not advisable.
2. Save the sqls statement as text
Run the command mysql .... . <Sqls. SQL, and then capture the output. This is also a method, but it seems that there should be a better way around the problem.
3 Use the mysqli: multi_query method
This method can execute multiple SQL statements, and then use mysqli: next_result to set the SQL offset. use mysqli: error to obtain the SQL error status of the current offset.
The following is the sample code of the third method.
The code is as follows:
The code is as follows:
$ SQL = Config: get ('SQL ');
$ Content = file_get_contents ($ SQL );
$ Config = Config: get ('config ')
$ Mysqli = mysqli_connect ($ config ['host'], $ config ['user'], $ config ['password'], $ config ['dbname']);
$ Ret = $ mysqli-> multi_query ($ content );
If ($ ret = false ){
Echo mysqli_error ($ mysqli );
}
While (mysqli_more_results ($ mysqli )){
If (mysqli_next_result ($ mysqli) === false ){
Echo mysqli_error ($ mysqli );
Echo "\ r \ n ";
Break;
}
}
$ Mysqli-> close ();
In this case, if any one of the sqls statements has an error, the program will jump out of the error.
If you want to write a script to initialize mysql, this method is very useful.