使用 Scope_Identity PHP 和 SQL Server 2008 插入到两个表中


Insert into two tables using Scope_Identity PHP and SQL Server 2008

我正在建立一个在线商店网站,让用户在线购买商品。用户单击"确认订单"后,将运行以下查询:

$tsql = "DECLARE @NewID INT
    INSERT INTO orders (orderDate, customerID, price_total) VALUES (GETDATE(),'$custID','$totalPrice')
    SELECT @NewID = SCOPE_IDENTITY()
    INSERT INTO order_items (orderID, price) VALUES ('@NewID', '$totalPrice')";
    $stmt = sqlsrv_query($conn,$tsql);

"订单"表中的订单 ID 列是主键,并且是自动递增的。我希望能够获取刚刚插入"订单"表中的订单ID,并将其与其他相关信息一起插入"order_items"表中。

记录确实会添加到"订单"表中,但不会添加到"order_items"表中。我不确定我的查询是否正确。我遵循了几个解释scope_identity的教程,但由于我对sql和php非常陌生,我可能在某处犯了一个错误。

写@NewID而不是用撇号"@NewID"呢?

INSERT INTO order_items (orderID, price) VALUES ('@NewID', '$totalPrice')";

应该是

INSERT INTO order_items (orderID, price) VALUES (@NewID, '$totalPrice')";

@NewID是SQL变量而不是您要传入的参数。