我发现 PDO 事务仅提交了 2 个 SQL 语句中的 1 个。由于某种原因,我的 PHP 脚本没有插入到我的 MySQL 数据库 'homes
' 表中,但它确实插入到 'invoices
' 表中 - 即使我使用的是PHP PDO 数据库事务。
代码如下:
$conn_str = DB . ':host=' . DB_HOST . ';dbname=' . DB_NAME;
$dbh = new PDO($conn_str, DB_USERNAME, DB_PASSWORD);
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();
$sql_create_home_listing = 'INSERT INTO homes ( customer_id,
account_type_id,
address,
city,
state,
zip,
display_status
) VALUES (?,?,?,?,?,?,true)';
$stmt = $dbh->prepare($sql_create_home_listing);
$stmt->bindParam(1, $customer_id);
$stmt->bindParam(2, $account_type_id);
$stmt->bindParam(3, $_SESSION['street']);
$stmt->bindParam(4, $_SESSION['city']);
$stmt->bindParam(5, $_SESSION['state']);
$stmt->bindParam(6, $_SESSION['zip']);
$stmt->execute();
$home_id = $dbh->lastInsertId();
// another SQL statement
$sql_create_invoice = "INSERT INTO invoices (customer_id, account_type_id, price, cc_authorized, home_id) VALUES (?,?,?,?,?)";
$cc_authorized = false;
$anotherStmt = $dbh->prepare($sql_create_invoice);
$anotherStmt->bindParam(1, $customer_id);
$anotherStmt->bindParam(2, $account_type_id);
$anotherStmt->bindParam(3, $account_plan_price);
$anotherStmt->bindParam(4, $cc_authorized);
$anotherStmt->bindParam(5, $home_id);
$anotherStmt->execute();
/* Commit the changes */
$dbh->commit();
怎么可能只有“invoices
”表获得插入,而不是“invoices
”表和“homes
” >'表?
注意:PHP 不会报告任何错误。
最佳答案
首先,检查 PHP 中是否真的有任何错误 - 众所周知,它告诉你的错误。您可以在 PDO 对象上设置一个选项,以在数据库错误时引发异常 - 我建议您设置它。
在我看来,它正在插入行,但您处于一个从未提交的事务中,因此它会回滚,并且该行永远不可见(您的隔离模式为 READ_COMMITTED 或更高)。
在这种情况下,您需要重新检查应用程序如何使用事务,并尝试查看是否可以使其保持适当的一致性。使用事务并不简单;它要么需要大量代码才能使事情正确,要么需要一些经过深思熟虑的包装代码或其他东西。如果您不明白其中任何一个,请将自动提交保持打开状态。
关于PHP:SQL 准备语句事务无法正常工作。它插入 1 个 SQL 语句,而不是两者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1562522/