简体   繁体   English

返回LastInsertID时,PDO事务回滚

[英]PDO Transaction rolling back when returning LastInsertID

I am having a strange problem which I don't understand. 我遇到一个奇怪的问题,我不明白。 I have the following function which is supposed to return $asset_ID: 我有以下功能,应该返回$ asset_ID:

function commit_purchase($asset_type_ID, $org_ID, $asset_desc, $asset_cost, $date, $org_to_member_ID, $asset_ID, $purchaser_cur_invest, $purchaser_cred_deb, $purchaser_balance) {
global $db;
$db->beginTransaction();
$query = "INSERT INTO assets
                       (asset_type_ID, org_ID, asset_desc, asset_cost, asset_value, purchase_date, is_approved)
                    VALUES
                       (:asset_type_ID, :org_ID, :asset_desc, :asset_cost, :asset_cost, :date, 1)";
$statement = $db->prepare($query);
$statement->bindValue(':asset_type_ID', $asset_type_ID);
$statement->bindValue(':org_ID', $org_ID);
$statement->bindValue(':asset_desc', $asset_desc);
$statement->bindValue(':asset_cost', $asset_cost);
$statement->bindValue(':date', $date);
$statement->execute();
$asset_ID = $db->lastInsertId();
//return $asset_ID;
$db->commit(); 
}

I am calling the function like so: 我这样调用函数:

$asset_ID = commit_purchase($asset_type_ID, $org_ID..etc, etc.);

If I uncomment the return $asset_ID , the transaction rolls back and does not commit. 如果我取消注释return $asset_ID ,则事务回滚并且不提交。 If I leave it commented, the variable is not passed. 如果我将其保留为注释,则不会传递变量。 If I comment out the beginTransaction and commit lines, I can uncomment the return $asset_ID and everything works. 如果我注释掉beginTransactioncommit行,则可以取消注释$asset_ID返回$asset_ID ,一切正常。

I want it to stay as a transaction and I want to return the $asset_ID . 我希望它作为事务保留,并且我想返回$asset_ID What am I doing wrong? 我究竟做错了什么?

You need to move the return $asset_ID; 您需要移动return $asset_ID; line to after the commit as the execution of the function stops when you return . 在提交后的一行到,因为return时函数的执行停止。 Without the commit being called you get an implicit rollback. 没有调用提交,您将隐式回滚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM