同时插入两个表
我必须一次将INERT INTO到两个表中,假设一个表是我的client_enquiry,另一个表是client_materials. 直到这里没问题,INSERT命令才能在两个表中正常工作.并且如果在第二张表(client_materials)上插入时发生了什么不好的事情?如果对表client_materials的INSERT命令失败,如何回滚"? 基本上我有这个:
I have to INSERT INTO two tables at once, let's say one table is my client_enquiry and another table is the client_materials. Until here it's okay, the INSERT command it's working in both tables. And If something bad happens when I'm inserting on the second table (client_materials)? How can I "rool back" if the INSERT command fails on table client_materials? Basically I have this:
$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();
执行您提到的回滚 .
$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设置为异常抛出模式
You just need to be sure that engine supports transactions and PDO is set into exception throwing mode