Vladimir Vladimir - 27 days ago 6
MySQL Question

MySQL 5.5 SIGNAL and PDO exceptions

I have a TRIGGER for a MySQL table which raises exception with SIGNAL when there's something wrong with the data provided. How can I catch this exception in PHP with PDO?

Thanks in advance.

UPDATE

More information on my problem: I am executing several queries within a transaction and I want to rollback the transaction if one of them fails because there was a SIGNAL. Currently a signal is activated but all the other queries are executed.

ANOTHER UPDATE

So far I've got:

try {
$db->beginTransaction();

if (!$db->query('UPDATE accounts SET amount = amount - 10 WHERE id = 1')) {
throw new Exception($db->errorInfo()[2]);
}

if (!$db->query('UPDATE accounts SET amount = amount + 10 WHERE id = 2')) {
throw new Exception($db->errorInfo()[2]);
}

$db->commit();
} catch (Exception $e) {
$db->rollback();
echo 'There was an error: ' . $e->getMessage();
}


Is this the proper way to do a transaction with handling the exceptions?
Sorry if my question is too broad.

Answer

Try something like:

$ls_error = "";
$mysqli->autocommit(FALSE);
// first sql
if (!$mysqli->query($sql)) {
    $ls_error .= sprintf("Error: %d: %s\n",$mysqli->errno,  $mysqli->error);
    $mysqli->rollback();
}
// second one
if ($ls_error == "") {
    if (!$mysqli->query($sql)) {
        $ls_error .= sprintf("Error: %d: %s\n",$mysqli->errno,  $mysqli->error);
        $mysqli->rollback();
    }
}

// third one
if ($ls_error == "") {
    if (!$mysqli->query($sql)) {
        $ls_error .= sprintf("Error: %d: %s\n",$mysqli->errno,  $mysqli->error);
        $mysqli->rollback();
    }
}
if ($ls_error == "") {
    $mysqli->commit();
} else {
    echo $ls_error;
}