Home  >  Article  >  Backend Development  >  Solution to execute batch mysql statements in PHP_PHP tutorial

Solution to execute batch mysql statements in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:11:24822browse

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);”

If you need to execute it, there are three methods that can be used in php:

mysql_query

pdo

mysqli

Three methods are available when there is no problem with the sqls statement.

But

Problems will occur when the sql statement is wrong
The first sql error: all three methods return false

The first sql is correct, the second sql is wrong: mysql_query, pdo, mysqli:query also return true. So At this time, you cannot judge whether the statement in your sqls is wrong.


There are several ways to solve this problem:

1 Parse sql statement
Split each sql statement for execution. This solves the problem of executing each statement separately. But this method has several more methods, so it is not advisable.

2 Save the sqls statement as text
Use cmd to execute the command mysql…. .< sqls.sql, and then capture the output. This is also a method, but it feels like it's going around the problem. There should be a better way.

3 Use the mysqli::multi_query method
This method can execute multiple sql statements, then use mysqli::next_result to set the sql offset, and use mysqli::error to get the current offset Error status of moved sql

The following is the sample code for the third method

The code is as follows:

Copy codeThe 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 "rn";
break;
}
}
$mysqli->close(); If there is an error in one line, the program will jump out of this error.
This is very useful if you want to write a script to initialize mysql.

http://www.bkjia.com/PHPjc/326878.html

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326878.htmlTechArticleWhen 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);” If it needs to be executed, there are three methods that can be used in PHP:...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn