LuckyLuke
LuckyLuke

Reputation: 49047

Returns false when running this query

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

Upvotes: 0

Views: 172

Answers (4)

roselan
roselan

Reputation: 3775

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)

Upvotes: 0

N.B.
N.B.

Reputation: 14060

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.

Upvotes: 0

nobody
nobody

Reputation: 10635

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.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270599

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().

Upvotes: 1

Related Questions