对于下面的这些查询,
/*----------------------------------------------------Update temporary-----------------------------------------------------------------*/
$con = new mysqli('localhost','aaa','bbb','db');
$sql1 = $con->prepare(" UPDATE temporary SET status = 1 WHERE cat_no = ? AND po_no = ?");
$sql1->bind_param('ss', $cat_no, $po_no);
$sql1->execute();
/*----------------------------------------------------Update products-------------------------------------------------------------*/
$sql2 = $con->prepare(" UPDATE products SET qty = ? WHERE cat_no = ? ");
$sql2->bind_param("ss", $qty, $cat_no);
$sql2->execute();
mysqli_close($con);
如何编写交易,以便:
1)如果任何一条语句执行失败,它将回滚到原始状态。
2)两个语句都成功执行,然后提交。
任何人都可以帮忙吗?
答案 0 :(得分:0)
尝试这样的事情:
try
{
$conn = new PDO("mysql:host=localhost;dbname=db","aaa","bbb");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Could not acquire database handle: ".$e->getMessage();
}
$stm1 = $conn->prepare("UPDATE temporary SET status = 1 WHERE cat_no = ? AND po_no = ?");
$stm2 = $conn->prepare("UPDATE products SET qty = ? WHERE cat_no = ?");
$conn->beginTransaction();
try
{
$stm1->execute(array($cat_no, $po_no));
$stm2->execute(array($qty, $cat_no));
$conn->commit();
}
catch (PDOException $e)
{
$conn->rollBack();
echo "SQL error = ".$e->getMessage();
}