I have a piece of PHP code, where I get the form data, do a DELETE on the database and then do INSERT all the data from the form.
I would like to increase the security of this code using the "transitions" in MySQL in try and catch. So that if the INSERT does not go well, the DELETE has no effect
Here is my code:
$res = $conn->query("DELETE FROM `pm_buonipasto`
WHERE idprimanota = '$idprimanota'
AND tipologia = '$tipologiascelta' ");
if (!$res) {
printf("Errormessage: %s
", $conn->error);
exit(0);
}
$insert = $conn->query("INSERT INTO `pm_buonipasto`
(`id`, `idprimanota`, `nome`,
`tipologia`, `prezzatura`, `qt`)
VALUES (NULL,'$idprimanota','$nome',
'$tipologia','$prezzatura','$qt')
");
if (!$insert) {
printf("Errormessage: %s
", $conn->error);
exit(0);
}
How can I use transaction with MySQL for doing commit and rollback?
Try this way:
mysql_query("BEGIN");
$query1 = mysql_query("YOUR MYSQL QUERY HERE");
$query2 = mysql_query("YOUR MYSQL QUERY HERE");
if ($query1 and $query2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}