pdo transaction
Release: 2016-07-25 09:05:54
Original
1046 people have browsed it
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
|
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
-
2024-10-22 09:46:29
-
2024-10-13 13:53:41
-
2024-10-12 12:15:51
-
2024-10-11 22:47:31
-
2024-10-11 19:36:51
-
2024-10-11 15:50:41
-
2024-10-11 15:07:41
-
2024-10-11 14:21:21
-
2024-10-11 12:59:11
-
2024-10-11 12:17:31