I have the following update of the users table
and a selection
which gives me the updated result
right after the update, and I am wondering if is it appropriate to use a transaction
here? Also if yes then am I using it right codewisely together with prepared statements
?
try {
// connect to the database
require 'connect.php';
// create an update query
$conn->beginTransaction();
$queryUpdate = $conn->prepare("UPDATE users SET userName=:userName, firstName=:firstName,
lastName=:lastName, password=:password, image=:image WHERE userId=:userId");
$queryUpdate->bindParam( ':userId' , $sUserId );
$queryUpdate->bindParam( ':userName' , $sNewUserName );
$queryUpdate->bindParam( ':firstName' , $sNewFirstName );
$queryUpdate->bindParam( ':lastName' , $sNewLastName );
$queryUpdate->bindParam( ':password' , $sNewPassword );
$queryUpdate->bindParam( ':image' , $sNewImagePath );
$bResult = $queryUpdate->execute();
// create another query to get some of the updated values
$querySelect = $conn->prepare("SELECT users.userName, users.firstName, users.lastName, users.image
FROM users WHERE userId=:userId");
$querySelect->bindParam( ':userId' , $sUserId );
// run query
$querySelect->execute();
$ajResult = $querySelect->fetch(PDO::FETCH_ASSOC);
// take each property one by one
$sUserName = $ajResult['userName'];
$sFirstName = $ajResult['firstName'];
$sLastName = $ajResult['lastName'];
$sImagePath = $ajResult['image'];
// i.e. no query has failed, and we can commit the transaction
$conn->commit();
$sjResponse = $bResult ? '{"status":"ok", "userName":"'.$sUserName.'", "firstName":"'.$sFirstName.'",
"lastName":"'.$sLastName.'", "image":"'.$sImagePath.'"}' : '{"status":"error"}';
echo $sjResponse;
} catch (Exception $e) {
// An exception has been thrown
// We must rollback the transaction
echo "ERROR";
$conn->rollback();
}