pdo transaction
-
- //pdo implements a simple example of mysql transaction processing
- /*
- implements a transaction that writes multiple pieces of data to the database
- insert into test values ('test123', 'test123')
- * /
- $type = 'mysql'; //The type of database to be connected
- $host = 'localhost'; //Database host
- $dbname = 'test'; //The name of the database to be selected
- $password = '' ;
- $username = 'root';
- $dsn = "{$type}:dbname={$dbname};host={$host}";
- try{
-
- //Connect to the database
- $pdo = new PDO($dsn, $username, $password);
- //Encoding
- $pdo->exec("set names utf8");
-
- //Set error prompt method
- $pdo->setAttribute(PDO: :ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
-
- //Open standard transaction
- $pdo->beginTransaction();
-
- //Construct sql statement
- //$sql = "insert into test values (?,?)" ;
- $sql = "insert into test values (:user, :password)";
- //Or use this sql statement: user :password is similar to the question mark function to bind parameters
-
- $stmt = $pdo->prepare( $sql);
-
- //Bind variables for variables in sql statements
- $stmt->bindParam(':user', $username);
- $stmt->bindParam(':password', $password) ;
-
- //Assign values to variables in sql statements
- $username = 'test123';
- $password = '123456';
-
- $stmt->execute();
-
- $rows = $stmt->rowCount ();
-
- if($rows<1){
- //Throw an exception if it fails
- throw new PDOexception('The first sql statement failed to execute! ', '01');
- }
- $username = 'hello123';
- $password = '123456';
- $stmt->execute();
-
- $rows = $stmt->rowCount ();
-
- if($rows<1){
- //Throw an exception if it fails
- throw new PDOexception('The execution of the second sql statement failed!', '02');
- }
- $ username = 'world123';
- $password = '123456';
- $stmt->execute();
-
- $rows = $stmt->rowCount();
-
- if($rows<1){
- //If it fails, throw an exception
- throw new PDOexception('The execution of the third sql statement failed!', '02');
- }
- //If no exception is thrown, all sql statements are successfully executed and the transaction is submitted.
- $pdo->commit();
-
-
- }catch(PDOexception $e){
-
- //If an exception is thrown, the transaction fails and the transaction is rolled back
- $pdo->rollback();
-
- //Output exception information
- echo $e->getCode().'-----'.$e->getMessage();
-
- $pdo = null;
-
- }
-
-
- ?>
Copy code
|