我发现PDO Transaction只提交了我的2个SQL语句中的1个。出于某种原因,我的PHP脚本没有插入到我的MySQL数据库“homes
”表中,但它确实插入到“invoices
”表中 - 即使我正在使用PHP PDO数据库事务。 / p>
以下代码:
$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没有报告任何错误。
答案 0 :(得分:2)
首先,检查一下你是否真的在PHP中有任何错误 - 这是出了名的废话告诉你。您可以在PDO对象上设置一个选项,以便在数据库错误时抛出异常 - 我建议您进行设置。
听起来像是在插入行,但是你处于一个永不提交的事务中,因此它会被回滚,并且该行永远不可见(你的隔离模式是READ_COMMITTED或更高)。
在这种情况下,您需要重新检查应用程序如何使用事务,并尝试查看是否可以使其正确一致。使用交易是不平凡的;它需要大量的代码来使事情正确,或者需要一些经过深思熟虑的包装代码或其他东西。如果您不理解其中任何一项,请保持自动提交。
答案 1 :(得分:0)
检查您的表是否是事务性的(InnoDB vs MyISAM作为示例..)。
可能想尝试catch,这样如果出现错误就可以回滚。这可能会给你一些见解。
答案 2 :(得分:0)
是否为display_status的有效值?
MySQL没有bool类型,也不具有预定义函数或常量。所以我的猜测是这是一个语法错误。
获得一些不错的错误处理。设置当出现SQL错误时抛出的选项(请参阅PDO文档!)
答案 3 :(得分:0)
我发现了问题。在我家的桌子上,我有一个被视为“独特”的字段,但它不是并且阻止插入发生