PDO php在一个函数中有两个语句,如果两个都是true,则提交其他回滚

时间:2015-04-29 08:56:46

标签: php mysql pdo

使用PHP PDO,有两个语句,想法是两个stmt1 并且stmt2是真的它应该提交否则它应该回滚,但正如我在这里看到的那样它没有得到回滚,如果stmt1为真,它将注释即使stmt2为假。

这是功能:

 public function insert() {

            //  try { $stmt1 = $this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
            $this->conn->beginTransaction();
            $stmt1 = $this->conn->prepare("INSERT into table1 (item,itemname,price)VALUES (:name, :itemname, :price)");

            $stmt1->bindParam(':name' ,                  $this->name);
            $stmt1->bindParam(':itemname' ,              $this->itemname);
            $stmt1->bindParam(':price' ,                 $this->price);
            $stmt1->execute();

            $stmt2 = $this->conn->prepare("INSERT into table2 (item,itemname,price) VALUES (:name, :itemname, :price)");

            $stmt2->bindParam(':name' ,                  $this->name);
            $stmt2->bindParam(':itemname' ,              $this->itemname);
            $stmt2->bindParam(':price' ,                 $this->price);
            $stmt2->execute();

            //} catch(PDOException $r){ echo $r->__toString();exit; }
            if($stmt1 && $stmt2){
                $this->conn->commit(); //This will save  changes
            } else {
                $this->conn->rollBack(); //This will undo  changes
            }

        }

    }

这里我检查了这个函数,如果stmt1为true,它将运行并将数据插入表一,即使stmt2为false

问题:如何保持运行stmt1然后运行stmt2,如果stmt1为false,则不应运行stmt2,如果stmt2为false,则还应回滚stmt1。

提前感谢。

1 个答案:

答案 0 :(得分:2)

试试这个:

public function insert() {

        //  try { $stmt1 = $this->conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $this->conn->beginTransaction();
        $stmt1 = $this->conn->prepare("INSERT into table1 (item,itemname,price)VALUES (:name, :itemname, :price)");

        $stmt1->bindParam(':name' ,                  $this->name);
        $stmt1->bindParam(':itemname' ,              $this->itemname);
        $stmt1->bindParam(':price' ,                 $this->price);
        //$stmt1->execute();

        $stmt2 = $this->conn->prepare("INSERT into table2 (item,itemname,price) VALUES (:name, :itemname, :price)");

        $stmt2->bindParam(':name' ,                  $this->name);
        $stmt2->bindParam(':itemname' ,              $this->itemname);
        $stmt2->bindParam(':price' ,                 $this->price);
        //$stmt2->execute();

        //} catch(PDOException $r){ echo $r->__toString();exit; }
        if($stmt1->execute() && $stmt2->execute()){
            $this->conn->commit(); //This will save  changes
        } else {
            $this->conn->rollBack(); //This will undo  changes
        }

    }

}