[英]Insert into two tables using Scope_Identity PHP and SQL Server 2008
I am building an online shop website that lets a user buy items online. 我正在建立一个在线商店网站,让用户在线购买商品。 Once the user clicks on "Confirm Order" the following query runs:
用户单击“确认订单”后,将运行以下查询:
$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);
orderID column in "orders" table is a primary key and is auto-incremented. “orders”表中的orderID列是主键,并且是自动递增的。 I want to be able to get that orderID that was just inserted in "orders" table and insert it in "order_items" table along with other relevant information.
我希望能够获得刚刚插入“orders”表中的orderID,并将其与其他相关信息一起插入“order_items”表中。
The record does get added to the "orders" table, but nothing gets added to the "order_items" table. 该记录确实被添加到“orders”表中,但没有任何内容添加到“order_items”表中。 I am not sure if my query is right.
我不确定我的查询是否正确。 I followed several tutorials that explained scope_identity but as I'm very new to sql and php I might have made a mistake somewhere.
我按照几个解释scope_identity的教程,但因为我对sql和php很新,我可能在某个地方犯了错误。
怎么样写@NewID而不是'@NewID'用撇号...
INSERT INTO order_items (orderID, price) VALUES ('@NewID', '$totalPrice')";
should be 应该
INSERT INTO order_items (orderID, price) VALUES (@NewID, '$totalPrice')";
@NewID is sql variable not a parameter you are passing in. @NewID是sql变量,而不是您传入的参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.