同时插入两个表

时间:2013-05-12 11:39:12

标签: pdo insert

我必须一次INSERT INTO两个表,假设一个表是我的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();

1 个答案:

答案 0 :(得分:2)

the very rollback you mentioned

$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 is set into exception throwing mode