Question

I am having a strange problem which I don't understand. I have the following function which is supposed to return $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. 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.

I want it to stay as a transaction and I want to return the $asset_ID. What am I doing wrong?

Was it helpful?

Solution

You need to move the return $asset_ID; line to after the commit as the execution of the function stops when you return. Without the commit being called you get an implicit rollback.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top