I always used PHP in procedural way using mysqli. Now I am working with interdependent queries so I am using transactions (if query1 ok then proceed with query2 and commit, if not rollback). I always used if/else to check the flow/errors, but now I have something more articulated so I would like to use try/catch, because I would not like to have to do thousands IF to check every single query.
Given this code (just an example):
<?php
try {
// disable autocommit
mysqli_autocommit( $db, FALSE );
// lock tables
$query = 'LOCK TABLES `table` WRITE, `other_table` WRITE';
mysqli_query( $db, $query );
// QUERY 1:
$query = 'SELECT `field` FROM `table` WHERE `id` = ?';
$stmt = mysqli_prepare( $db, $query );
if ( $stmt ) {
// bind parameters
mysqli_stmt_bind_param( $stmt, 'i', $_POST[ 'id' ] );
// execute query
mysqli_stmt_execute( $stmt );
// bind result
mysqli_stmt_bind_result( $stmt, $stmt_result );
}
// QUERY 2 INTERDEPENDENT FROM QUERY 1:
$query = 'DELETE FROM `other_table` WHERE `id` = ?';
$stmt = mysqli_prepare( $db, $query );
if ( $stmt ) {
// bind parameters
mysqli_stmt_bind_param( $stmt, 'i', $stmt_result );
// execute query
mysqli_stmt_execute( $stmt );
}
// unlock tables
$query = 'UNLOCK TABLES';
mysqli_query( $db, $query );
///////////////////////////////////////////////////////////////
// //////// IF SCRIPT ARRIVES HERE IT MEANS EVERYTHING IS OK:
///////////////////////////////////////////////////////////////
// Commit
mysqli_commit( $db );
// re-enable autocommit
mysqli_autocommit( $db, TRUE );
}
///////////////////////////////////////////////////////////////
// //////// IF ANYTHING GIVES ERROR/THROW EXCEPTION HANDLE IT:
///////////////////////////////////////////////////////////////
catch ( Exception $e ) {
// rollback
mysqli_rollback( $db );
// re-enable autocommit
mysqli_autocommit( $db, TRUE );
// show error
$_SESSION[ 'alert' ] = "ERROR";
$_SESSION[ 'messaggio' ] = "Error: " . $e->getMessage();
mysqli_close( $db );
header( "Location: output.php" );
exit();
}
?>
My questions are:
1- is it possible (and correct) to use procedural mysqli prepared statements in a try/catch?
2- is ok to proceed that way? I mean keep all the queries of the transaction and theirs execution in a TRY, so all the errors are catched by its own CATCH?
3- is it ok to use always the same variable $stmt like I wrote in the code or do I need to close it every time with mysqli_stmt_close($stmt) before proceed with next prepare?
4- where i wrote comment:
// IF SCRIPT ARRIVES HERE IT MEANS EVERYTHING IS OK:
am I right or I THINK to be right?
I hope all is clear and to receive several answers because apart of the code, I am not sure if the way to proceed is correct, I would not like to have to do thousands IF to check every single query, I am sure there is a better way.
Thanks everyone in advance if you want to give me a feedback