0

我有一个 PHP 函数,它将多条记录插入 MySQL:

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;
    $query = "START TRANSACTION;
          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);
          SET @asset_ID = LAST_INSERT_ID();
          INSERT INTO cash_out
            (org_to_member_ID, amount, description, date, is_approved, asset_ID)
          VALUES
            (:org_to_member_ID, :asset_cost, :asset_desc, :date, 1, @asset_ID);
          SET @cash_out_ID = LAST_INSERT_ID();
          INSERT INTO shares
            (asset_ID, member_ID, percent_owner, is_approved)
          SELECT assets.asset_ID, pending_asset_shares.member_ID, pending_asset_shares.percent_owner, pending_asset_shares.is_approved
          FROM assets, pending_asset_shares
          WHERE assets.asset_ID = @asset_ID;
          DELETE FROM pending_asset_shares
          WHERE asset_ID = :asset_ID;
          DELETE FROM pending_assets
          WHERE pending_asset_ID = :asset_ID;
          INSERT INTO trans_log
             (translog_id, trans_type, org_to_member_ID, date, purchaser, asset_ID, cur_invest, cash_out_ID, cred_deb, balance)
          VALUES
             (DEFAULT, 3, :org_to_member_ID, :date, :org_to_member_ID, @asset_ID, :purchaser_cur_invest, @cash_out_ID, :purchaser_cred_deb, :purchaser_balance);
          COMMIT;";
$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->bindValue(':org_to_member_ID', $org_to_member_ID);
$statement->bindValue(':purchaser_cur_invest', $purchaser_cur_invest);
$statement->bindValue(':purchaser_cred_deb', $purchaser_cred_deb);
$statement->bindValue(':purchaser_balance', $purchaser_balance);
$statement->bindValue(':asset_ID', $asset_ID);
$statement->execute();
$statement->closeCursor();
return $asset_ID;

我正在尝试使用第一个 INSERT 语句的 LAST_INSERT_ID (@asset) 作为我下一个函数的变量。为了设置变量,我调用上述函数的方式是:

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

我很确定我的问题出在我的 SQL 语句中的“return $asset_ID”附近。仅使用 1 个 LAST_INSERT_ID 调用时,我已经能够成功地做到这一点。

根本没有任何东西被退回。

4

2 回答 2

0

好的,正如我在评论中提到的,你可以用它beginTransaction来打破它。 http://php.net/manual/en/pdo.begintransaction.php

完成此操作后,只需获取最后插入的 ID。您可以使用lastInsertId:http: //php.net/manual/en/pdo.lastinsertid.php

于 2012-03-23T18:58:25.443 回答
0

将其分解为多个查询确实是最好的解决方案,但要回答您最初的问题:如果您想在 PHP 中获取 MySQL 变量的值,只需执行 SELECT 查询:

$asset_ID = mysql_result( mysql_query( 'SELECT @asset_ID' ) );
于 2012-03-23T19:04:29.777 回答