try{ $pdo =new PDO ("Mysql:host=localhost;dbname=psp", "Root", ""); $pdo->exec ("Set names UTF8"); $pdo->setattribute (pdo::attr_errmode,pdo::errmode_exception);//Set exception handling mode $pdo->setattribute (pdo::attr_autocommit,0);//Turn off autocommit }catch (Pdoexception $e) { echo "Database connection failed"; Exit } try{ $age = 10; $pdo->begintransaction ();//Start 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 '");//arbitrarily change to make it perform successfully or fail /* IF ($affected _rows1&& $affected _rows2) { $pdo->commit (); Echo "Operation succeeded"; }else{ $pdo->rollback (); } */ if (! $affected _rows1) throw new Pdoexception ("Add error"); if (! $affected _rows2) throw new Pdoexception ("reduce error"); Echo "Operation succeeded"; $pdo->commit ();//If the execution of the previous two update SQL statement succeeds, the entire transaction executes successfully }catch (Pdoexception $e) { Echo "Operation failed:". $e->getmessage (); $pdo->rollback ();//The statement in the execution transaction is out of the question and the whole transaction is undone } $pdo->setattribute (pdo::attr_autocommit,1); Whether the test was successful echo "\ nthe operation result is: \ n"; $sql = "SELECT * from Kfry"; $result = $pdo->query ($sql); foreach ($result as $v) { echo $v [' K_name ']. " ". $v [' K_age ']." \ n "; } ?> |