Any reasons why this not work? When I print the query to screen and runs it through phpMyAdmin it works. I left out the part where I c开发者_开发问答onnect to the database (MySQL).
$query = "START TRANSACTION; ";
$query .= "INSERT INTO table1(text) VALUES('$question_description'); ";
for ($i = 0; $i < count($processed_answers); $i++) {
$query .= "INSERT INTO table2(question_id, text, serial_number, is_correct) ".
"VALUES($question_id, '".$processed_answers[$i]."', '".$serial_numbers[$i]."', 0); ";
}
foreach($categories as $category) {
$query .= "INSERT INTO table3 VALUES($question_id, $category); ";
}
$query .= "COMMIT; ";
$result = $db->query($query);
Looks like you are attempting to run multiple statements, possibly through a mysql_query()
or mysqli->query()
which only support single statements. Instead you need to execute this with mysqli->multi_query()
or mysql_multi_query()
.
You are trying to run multiple queries at once, you should either run those queries one at a time or use the mysqli::multi_query method.
You're trying to run multiple queries by creating a string that contains them and then you send it to the DB. It looks like your database object doesn't support that, and the only way you can run multiple queries is by using mysqli's multi_query
function.
However, there's a drawback - what if the transaction doesn't commit? What if there's an error? Where's the rollback and the error message?
PDO would be my choice here, with try/catch block and I'd create a prepared statement that I'd send rather than a huge string containing all the queries. Not only is it more elegant, it's easier to debug too.
mysql_query doesn't support multiple queries
check this php manual comment for more info. In short. you should call $db->query instead of appending to $query.
note. transactions works only with innodb (at least last time I checked)
精彩评论