使用 PHP PDO,有两个语句,想法是 if both 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 为真,即使 stmt2 为假,它也会运行并将数据插入表一
问题:我如何保持运行 stmt1 然后运行 stmt2 的状态,如果 stmt1 为假,则不应运行 stmt2,如果 stmt2 为假,则还应回滚 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
}
}
}
关于php - PDO php 两个语句在一个函数中,如果都为真,则提交,否则回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29938861/