我这里有一张与客户订单相对应的表格。我AUTO_INCREMENT
用来确定订单的ID。我在orders
表中有此SQL代码:
CREATE TABLE IF NOT EXISTS `orders` (
`order_id` int(11) NOT NULL AUTO_INCREMENT,
`customer_id` int(11) NOT NULL,
`customer_name` varchar(500) NOT NULL,
`order_total_price` decimal(20, 2) NOT NULL,
`order_date` varchar(100) NOT NULL,
PRIMARY KEY (`order_id`)
) ENGINE=InnoDB
我需要将该订单的每个产品插入带有外键的另一个表中,order_id
以指定产品所属的订单。该purchased_products
表的SQL代码为:
CREATE TABLE IF NOT EXISTS `purchased_products` (
`order_id` int (11) NOT NULL,
FOREIGN KEY (`order_id`) REFERENCES orders(`order_id`),
`product_name` varchar(500) NOT NULL,
`product_price` decimal(20, 2) NOT NULL,
`product_quantity` int(11) NOT NULL,
PRIMARY KEY (`order_id`)
)
当用户购买东西时,我使用它在orders
表中插入数据:
INSERT INTO orders (customer_id, customer_name, order_total_price, order_date)
VALUES ('{$customer_id}', '{$customer['customer_name']}', '{$order_total_price}', '{$order_date}')";
这是我的问题。我需要在purchased_products
表中插入生成了订单ID的产品:
INSERT INTO purchased_products (order_id, product_name, product_price, product_quantity)
VALUES ('*/The ID of the order need to goes here*/', '{$product['product_name']}', '{$product['product_price']}', '{$product['quantity']}')";
这让我头疼。我真的不知道该怎么做。这应该以其他方式完成吗?如何将订单ID与所属产品关联?
我通过使用PDOlastInsertId()
来获取上次插入订单的ID:
$sql = "INSERT INTO orders (customer_id, customer_name, order_total_price, order_date)
VALUES ('{$customer_id}', '{$customer['customer_name']}', '{$order_total_price}', '{$order_date}')";
$query = $connection->prepare($sql);
$query->execute();
$respective_order_id = $connection->lastInsertId();
接着:
INSERT INTO purchased_products (order_id, product_name, product_price, product_quantity)
VALUES ('{$respective_order_id}', '{$product['product_name']}', '{$product['product_price']}', '{$product['quantity']}')";
感谢所有尝试提供帮助的人!他们以正确的方式给我!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句