0

I want to use Transaction in my PHP code. i search and found solution to implement it. but i don't know my code is correctly work or not by this implementation. i need to insert new user in table if condition was ok, commit it, otherwise rollback inserted data. but i don't know if i don't commit insert statement i need to rollback it in false part or not. please guide me. i need to know if my insert query has error and else part is execute, the rollback() method what do in this situation? is it ok or make rollback another query and make invalid side effect??

$json = array();
$db->autocommit(FALSE);
$query_insert = sprintf("INSERT INTO tbl_user_x (user_email,user_password,user_reg_date,user_type_id_fk) VALUES ('%s','%s','%s','%s')",
    $db->real_escape_string($email),
    $db->real_escape_string(md5($password)),
    $db->real_escape_string($regdate),
    $db->real_escape_string($user_type)
);
$result_insert = $db->query($query_insert);
if ($db->affected_rows != 0 && !$db->error) {
    $json['result_action'] = "successful";
    $json['result_error'] = "null";
    $db->commit();
} else {
    $json['result_action'] = "fail";
    $json['result_error'] = $db->error;
    $db->rollback();
}
header("Content-type: application/json");
echo json_encode($json, JSON_UNESCAPED_UNICODE);
Hamed Taheri
  • 164
  • 2
  • 11
  • `if( $db->query($query_insert) ){ success }else{ error } ` – Sandun Chathuranga Aug 18 '16 at 11:50
  • so u executed this, just create a common function so that it can be used in other place too – AmmyTech Aug 18 '16 at 11:51
  • 1
    You are only doing ONE INSERT. If it fails it will not update the database, so basically there is no reason to worry about providing a commit/rollback for this example. You need to implement this idea when you are changing 2 or more rows where if the second one fails it would mean the first update would be left stranded and damage the integrity of your database – RiggsFolly Aug 18 '16 at 11:53

0 Answers0