PHP execution Batch MySQL statement solution _php Instance

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.