我有一个脚本,其中包含一些查询:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
如您所见,有两个语句(insert
和update
)。我所要做的就是确保它们都能工作,或者一个都不工作。
我的意思是,我想实现这两个语句之间的依赖关系。如果更新失败,则插入不起作用,反之亦然。我该怎么做?
您可以使用sql事务http://www.sqlteam.com/article/introduction-to-transactions
您可以使用事务,PDO有一个api(http://php.net/manual/en/pdo.begintransaction.php),
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
正如其他人所说,您可以使用"transactions"。
或者您可以手动检查数据库中的数据是否正确。只需"选择"您插入的内容。
"execute"函数在成功时返回"true",在失败时返回"false"。你可以做一些类似的事情:
$isDone=$stm1->execute(array($value));
if(!$isDone){
echo 'Operation fails, I will stop.';
return false;
}