简体   繁体   中英

PDO - Multiple inserts / updates in one query

I wrote some code that built up a single query of multiple insert and update statements which was executed at the end of a page load. It used to work okay. I am writing similar, optimised code on my dev system (Ubuntu 14.04, PHP 5.5.3-Ubuntu), but I am no longer able to run multiple statements in one PDO query:

What I do

During a page render, I build up an SQL statement that would look a bit like:

insert into <table> (col1,col2,col3) VALUES (?,?,?);
update <table> set col1 = ?, col4 = ? where id = ?;
insert into <table> (col1,col2,col3) VALUES (?,?,?);
...

When the page has been rendered and I'm sure there are no problems, I execute the query using a wrapper for PDO. The important bits of the wrapper function are

$database = new PDO("mysql:host=<host>;dbname=<dbname>", <user>, <pwd>, 
               array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names 'utf8'"));
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $database->prepare($sql);
$stmt->execute($params);

For some reason, I am no longer able to execute this statement in one hit, instead, PDO only performs the first query, despite $stmt->queryString still holding the whole query. Can anyone help me with this problem.

Found the problem: PDO fails silently if one of the queries throws an exception. In my case, the first query was okay, but the second was throwing an integrity constraint failure error, so it looked like only the first query was being run.

A wise man just told me: Don't shoot the messenger , break the queries up

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM