When there are multiple MySQL statements that need to be executed, such as
$sqls = "Insert Table A values (1,2); Insert Table A values (2,3);
There are three methods that you can use in PHP if you need to do this:
Mysql_query
Pdo
Mysqli
Three methods are OK when the SQLS statement is not a problem.
But
The problem occurs when the SQL statement is wrong
First SQL Error: three methods return false
The first SQL is correct, and the second SQL error: mysql_query, PDO, Mysqli:query also returns True. So at this point you can't tell if your sqls has that statement wrong.
There are several ways to solve this problem:
1 Parsing SQL statements
Each SQL is split to execute. So that each statement is executed separately. But there are several ways to do this, so it is not advisable.
2 Save the SQLS statement as text
Use cmd to execute command mysql ..... < Sqls.sql, and then capture the output. This is also a method, but the feeling is to go around the problem, there should be a better way.
3 Using the Mysqli::multi_query method
This method can execute more than one SQL statement, and then use Mysqli::next_result to set the SQL offset, using Mysqli::error to get the current offset SQL error status
The following is a sample code for the third method
The code is as follows:
Copy Code code 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 of the SQLS statements have errors, the program will jump out of the error.
If you're going to write a script that initializes MySQL, it's pretty handy.