0

我必须一次插入两张表,假设一张表是我的 client_enquiry,另一张表是 client_materials。直到这里没关系,它在两个表中都可以使用的 INSERT 命令。如果我在第二张表(client_materials)上插入时发生了不好的事情?如果 INSERT 命令在表 client_materials 上失败,我该如何“回滚”?基本上我有这个:

 $sql_table1 = "INSERT INTO client_enquiry (reference, date) VALUES ('REF', '2013-05-12')";
 $q = $conn->prepare($sql_table1);
 $q ->execute();

 $Last_ID = $conn->lastInsertId('id_enquiry');

 $sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date) 
    VALUES (".$Last_ID."'Description', '2013-05-12')";
 $q = $conn->prepare($sql_table2);
 $q -> execute();
4

1 回答 1

2

你提到回滚

$conn->beginTransaction();
try
{
    $sql = "INSERT INTO client_enquiry (reference, date) VALUES (?,?)";
    $q = $conn->prepare($sql);
    $q ->execute(array('REF', '2013-05-12'));

    $Last_ID = $conn->lastInsertId();

    $sql_table2 = "INSERT INTO client_materials (id_client_enquiry,description, date) 
                   VALUES (?,?,?)";
    $q = $conn->prepare($sql);
    $q -> execute(array($Last_ID, 'Description', '2013-05-12'));

    $conn->commit();

}
catch (PDOException $e)
{
    $conn->rollback();
    throw $e;
}

您只需要确保引擎支持事务并且PDO 设置为异常抛出模式

于 2013-05-12T11:59:52.197 回答