Try { $ Pdo = new PDO ("mysql: host = localhost; dbname = psp", "root ",""); $ Pdo-> exec ("set names utf8 "); $ Pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION); // sets the exception handling mode. $ Pdo-> setAttribute (PDO: ATTR_AUTOCOMMIT, 0); // disable automatic submission } Catch (PDOException $ e ){ Echo "database connection failed "; Exit; } Try { $ Age = 10; $ Pdo-> beginTransaction (); // start the transaction $ Affected_rows1 = $ pdo-> exec ("update kfry set k_age = k_age + {$ age} where k_name = 'user1 '"); $ Affected_rows2 = $ pdo-> exec ("update kfry set k_age = k_age-{$ age} where k_name = 'user2'"); // modify it to make it successful or failed at will /* If ($ affected_rows1 & $ affected_rows2) { $ Pdo-> commit (); Echo "operation successful "; } Else { $ Pdo-> rollback (); }*/ If (! $ Affected_rows1) Throw new PDOException ("add error "); If (! $ Affected_rows2) Throw new PDOException ("reduce errors "); Echo "operation successful "; $ Pdo-> commit (); // if the first two updated SQL statements are successfully executed, the entire transaction is successfully executed. } Catch (PDOException $ e ){ Echo "operation failed:". $ e-> getMessage (); $ Pdo-> rollback (); // An error occurred while executing the statement in the transaction. The entire transaction is canceled. } $ Pdo-> setAttribute (PDO: ATTR_AUTOCOMMIT, 1 ); // Test whether the task is successful Echo "\ n operation result: \ n "; $ SQL = "select * from kfry "; $ Result = $ pdo-> query ($ SQL ); Foreach ($ result as $ v) { Echo $ v ['K _ name']. ". $ v ['K _ age']." \ n "; } ?> |