Hi guys.
I have been using PDO to handle a MySQL database, and also have been trying to do it with transactions.
However, in the script below I am not getting the transaction enforced:
- the SQL queries are ok. If I dont mess them up, everything goes fine and both statements are written to the database.
- if I mess any of the SQL statments, I would expect that none of them would be written to the database. The exception does get thrown, and I do get the echoed error message on the screen but the correct SQL statement does not get rolled back as it is supposed to be and is still written.
Can any of you let me know what am I doing wrong here?
PHP Code:
try {
// habilita as excepções
$dbwrite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// inicia a transacção
$dbwrite->beginTransaction();
// realiza a primeira operação de escrita
$stringUpdate="
update tabela1
set campo1= :conteudo1_,
campo2= :conteudo2_,
campo3= :conteudo3_
where umaCondicaoQualquer
";
$pedido=NULL;
$pedido=$dbwrite->prepare($stringUpdate);
// limpa as variáveis que vai escrever na bd
$pedido->bindParam(':conteudo1_', $_POST['post1'], PDO::PARAM_INT);
$pedido->bindParam(':conteudo2_', $_POST['post2'], PDO::PARAM_INT);
$pedido->bindParam(':conteudo3_', $_POST['post3'], PDO::PARAM_STR);
$pedido->execute();
// realiza a segunda operação de escrita
$stringUpdate="
update tabela2
set campoA= :conteudoA_,
campoB= :conteudoB_,
campoC= :conteudoC_
where outraCondicaoQualquer
";
$pedido=NULL;
$pedido=$dbwrite->prepare($stringUpdate);
// limpa as variáveis que vai escrever na bd
$pedido->bindParam(':conteudoA_', $_POST['postA'], PDO::PARAM_INT);
$pedido->bindParam(':conteudoB_', $_POST['postB'], PDO::PARAM_INT);
$pedido->bindParam(':conteudoC_', $_POST['postC'], PDO::PARAM_STR);
$pedido->execute();
// finaliza a escrita das duas operações
$dbwrite->commit();
}
// se ocorreu uma excepção
catch (Exception $e) {
// desfaz toda a operação
$dbwrite->rollBack();
echo $e;
}
__________________
You can allways find me at www.datagen.eu, I own it.
And if you are hiring, I 'm all ears, now.