Home  >  Article  >  Backend Development  >  Detailed introduction to transaction processing in PDO

Detailed introduction to transaction processing in PDO

黄舟
黄舟Original
2017-04-28 17:47:112373browse

Detailed introduction to transaction processing in PDO

A transaction is composed of a sequence of query and/or update statements. Use begin and start transaction to start a transaction, rollback to roll back the transaction, and commit to commit the transaction. After starting a transaction, there can be several SQL queries or update statements. After each SQL is submitted for execution, there should also be statements to determine whether it is executed correctly to determine whether to roll back in the next step. If all are executed correctly, the transaction is finally committed. Once a transaction is rolled back, the database remains in the state it was in before the transaction started. It is like if an edited file is exited without saving, the original appearance of the file will be retained. Therefore, a transaction can be regarded as an atomic operation. The SQL in the transaction is either executed entirely or not at all.

In the first two articles "Error handling method one in PDO-errorCode() method", "Error handling method two in PDO-errorInfo() method》We have introduced the method of handling errors in PDO, then let us introduce the transaction processing in PDO in detail~

The function of transaction processing can also be realized in PDO, and its application method is as follows:

(1) Open the transaction-beginTransaction() method.

The beginTransaction() method will turn off the autocommit (autocommit) mode and will not resume until the transaction is committed or rolled back.

(2) Submit transaction - commit() method

The commit() method completes the transaction submission operation and returns true if successful, otherwise it returns false.

(3) Transaction rollback - rollBack() method

The rollBack() method performs the rollback operation of the transaction.

Add data to the database through the prepare() and execute() methods, and ensure that the data can be correctly added to the database through the transaction processing mechanism. The specific steps are as follows:

Create a php file , first define the database connection parameters, create a try{...}catch{...} statement, instantiate the PDO constructor in the try{} statement, complete the connection with the database, and start the transaction through the beginTransaction() method, and then Define the INSERT statement, obtain the data submitted in the form through the $_POST[] method, add data to the database through the prepare() and execute() methods, and complete the transaction submission operation through the commit(0 method, and finally catch{} The error message is returned in the statement, and the rollback operation of the transaction is performed through the rollBack() method. The specific code is as follows:

<form action="3.php" name="form1" method="post">
    用户名:<input type="text" name="username">
    密码:  <input type="password" name="password">
    <input type="submit" name="Submit" value="提交">
</form>
<?php
header("Content-Type:text/html; charset=utf-8");    //设置页面的编码格式
$name =$_POST[&#39;username&#39;];
$password =$_POST[&#39;password&#39;];
if($_POST[&#39;username&#39;]!=""&&$_POST[&#39;password&#39;]!=""){
    $dbms = "mysql";                                  // 数据库的类型
    $dbName ="php_cn";                                //使用的数据库名称
    $user = "root";                                   //使用的数据库用户名
    $pwd = "root";                                    //使用的数据库密码
    $host = "localhost";                              //使用的主机名称
    $dsn  = "$dbms:host=$host;dbname=$dbName";
try{
    $pdo=new PDO($dsn,$user,$pwd);//初始化一个PDO对象,就是创建了数据库连接对象$pdo
    $pdo -> beginTransaction();   //开始事务
    $query="insert into `user`(username,password) VALUES (&#39;$name&#39;,&#39;$password&#39;)";//需要执行的sql语句
    $res=$pdo->prepare($query);//准备查询语句
    $res->execute();            //执行查询语句,并返回结果集
    if($res->errorCode()){
        echo "数据添加成功";
    }else{
        echo "数据添加失败";
    }
    $pdo->commit();            //执行事务的提交操作
}catch (PDOException $e){
    die("Error!:".$e->getMessage().&#39;<br>&#39;);
 $pdo -> rollBack();             //执行事务的回滚
}
}
?>

The final output result is as follows:

Detailed introduction to transaction processing in PDO

After reading the transaction processing we introduced above, do you think it is very simple? You can contact us to consolidate what you have learned. In the next article, we will continue to introduce the storage process in PDO. For details, please read "Detailed introduction to stored procedures in PDO》!

The above is the detailed content of Detailed introduction to transaction processing in PDO. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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