我有两个通过外键关联的表。
要注册用户,我想连续将他的信息插入到 info 表中,并将凭据插入到 access 表中。
但是当第二次插入失败(出于任何原因)时,我想取消(删除)第一个插入。
这是部分代码:
// Data going to table "info"
$info = array(
"fname" => $_POST["fname"],
"lname"=> $_POST["lname"]
);
// if insert into table "info" is successfull
if ($lastInsertID = $this->model->addUser("info", $info)) {
// Data going to table "access"
$access = array(
"id" => $lastInsertID,
"password" => $_POST["password"],
"group" => "users",
"privilege" => 0,
);
// insert into table "access"
if ($this->model->addUser("access", $access)) {
echo json_encode(array("success"));
}
else {
// if insert into table "access" fails
// remove the last insert into table "info"
$this->model->deleteUser("info", $lastInsertID);
echo json_encode(array("error", "access"));
}
}
else echo json_encode(array("error", "info"));
问题是,如果第二次插入(在表“access”中)失败,则不会执行删除表“info”中最后一个插入的代码。我只得到返回 SQLSTATE 异常 和表“info”中的单行仍然
如何改进我的代码?或者有没有更好的方法来处理 php 和 postgresql 的“连续插入”?
使用交易:
您可以开始交易。然后执行addUser()。
如果您的操作成功,COMMIT,否则ROLLBACK。
在模型类中添加一些简单的包装方法:
// I don't know your names (class name, variable names, ...), So I use sample names
class DataModel {
/* your current code */
public function beginTransaction()
{ $this->db_connection->beginTransaction(); }
public function commit()
{ $this->db_connection->commit(); }
public function rollBack()
{ $this->db_connection->rollBack(); }
}
现在在代码中调用事务方法:
// Begin a transaction
$this->model->beginTransaction(); // <=====
// Data going to table "info"
$info = array(
"fname" => $_POST["fname"],
"lname"=> $_POST["lname"]
);
// if insert into table "info" is successfull
if ($lastInsertID = $this->model->addUser("info", $info)) {
// Data going to table "access"
$access = array(
"id" => $lastInsertID,
"password" => $_POST["password"],
"group" => "users",
"privilege" => 0,
);
// insert into table "access"
if ($this->model->addUser("access", $access)) {
// Commit changes; Write changes to database actually.
$this->model->commit(); // <=====
echo json_encode(array("success"));
}
else {
// if insert into table "access" fails
// RollBack; Cancel all changes you make in your transaction.
$this->model->rollBack(); // <=====enter code here
echo json_encode(array("error", "access"));
}
}
else echo json_encode(array("error", "info"));