使用PHP PDO时,有两个语句,其想法是:如果stmt1和stmt2都为true,则应提交,否则应回滚,但是正如我在这里看到的那样,它不会回滚,并且如果stmt1为true,它将连注释。 stmt2为false。
这是功能:
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。
提前致谢。
尝试这个:
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
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句