繁体   English   中英

如何使用 php mysql 在表中插入 last_insert_id 作为多个数据?

[英]How to insert last_insert_id as multiple data in a table using php mysql?

我有order_detail表,其结构如下:

在此处输入图像描述

order_idorder表中的外键。 在更新级联和删除级联上。 这不是自动增量。 所以基本上,对于一个订单,它可能有多个产品将插入order_detail

例如:id = 4 的orderorder_detail中有 3 个产品,其中 product_id = 1、2、3。但它们具有相同的 order_id (order_id = 4)。 如果我只有一个产品要插入 order_detail,则可以使用 LAST_INSERT_ID() 填充 order_id。 但是如果我有不止一个呢? 我已经尝试过自己的方法,但仍然无法正常工作。 这是我的代码

for ($i = 0; $i < count($product_id); $i++) {
    $productId = $product_id[$i];
    $totalProduct = $total_product[$i];
    $order_detail = mysqli_query($con, "INSERT INTO order_detail (order_id, product_id,
    total_product, total_price) VALUES ('LAST_INSERT_ID([$i])', '$productId', '$totalProduct', 
    null)")or die ("Gagal update".mysqli_error($con));
}

它返回的消息错误如下:

Cannot add or update a child row: a foreign key constraint fails (`rz_shop`.`order_detail`, CONSTRAINT `order_detail_order_id_foreign_key` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

那么如何从 id 的order表中插入相同的 order_id,不止一个但一次插入? 我真的希望你能帮助我解决这个问题。 提前致谢。

order表和order_detail表是“一对多”关系,使用order_id作为外键,那么过程应该是:

  1. order_detail需要作为 ID 自动递增(必填)

  2. 将插入过程分为 2 个步骤

// Insert `order` table
mysqli_query($connection, "INSERT INTO order VALUES (....................)");

// Get Last Insert ID (order_id)
$insert_id = mysqli_insert_id($connection);

// Count your product list
$total = count($product_list);

// Loop product list
for ( $i = 0; $i < $total ; $i++ ) {

   // Insert `order_detail` table
   $sql = "INSERT INTO order (id, order_id, product_id, total_product, total_price)
           VALUES (NULL, $insert_id, $product_id, $total_product, $total_price)";

   mysqli_query($connection, $sql);
}

在上面,您正在循环 $i 值,因此每次 $i 值更改时。 您需要将插入 ID 存储在单独的变量中。 像这样

$InsId=$last_ins_id(); //assign the insert Id in variable

然后在循环中使用 $InsId 而不是 LAST_INSERT_ID([$i])

for ($i = 0; $i < count($product_id); $i++) {
    $productId = $product_id[$i];
    $totalProduct = $total_product[$i];
    $order_detail = mysqli_query($con, "INSERT INTO order_detail (order_id, product_id,
    total_product, total_price) VALUES ('$InsId', '$productId', '$totalProduct', 
    null)")or die ("Gagal update".mysqli_error($con));
}

根据我的代码,我已经从这里的答案中实现了解决方案,这是解决问题的最终代码:

$insert_id = mysqli_insert_id($con);

for ($i = 0; $i < count($product_id); $i++) {
   $productId = $product_id[$i];
   $totalProduct = $total_product[$i];
   $order_detail = mysqli_query($con, "INSERT INTO order_detail (order_id, product_id, total_product, total_price) VALUES ('$insert_id', '$productId', '$totalProduct', null)")or die ("Gagal update".mysqli_error($con));
}

非常感谢大家。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM