gpt4 book ai didi

php - 如何在foreach中插入多条记录

转载 作者:可可西里 更新时间:2023-11-01 08:23:32 25 4
gpt4 key购买 nike

我试图在 foreach 循环中插入多条记录,这真的让我抓狂,因为它只插入第一条记录然后停止。你能帮我知道我的问题出在哪里吗?

foreach ($_SESSION["cart_products"] as $cart_itm) {
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
//$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty

$result = "insert into ordered (product_name, product_price) values ('$product_name',$product_price)";
if (mysqli_query($mysqli, $result)) {
echo "New record created successfully";
}
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$product_price.'RY</td>';
echo '<td>'.$subtotal.'RY</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}

最佳答案

你可以试试这个。这将通过单个查询插入所有数据。

<?php
$queryData = [];
foreach ($_SESSION["cart_products"] as $cart_itm)
{
//set variables to use in content below
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
//$product_color = $cart_itm["product_color"];
$subtotal = ($product_price * $product_qty); //calculate Price x Qty

$queryData[] = "('$product_name',$product_price)";
$bg_color = ($b++%2==1) ? 'odd' : 'even'; //class for zebra stripe
echo '<tr class="'.$bg_color.'">';
echo '<td><input type="text" size="2" maxlength="2" name="product_qty['.$product_code.']" value="'.$product_qty.'" /></td>';
echo '<td>'.$product_name.'</td>';
echo '<td>'.$product_price.'RY</td>';
echo '<td>'.$subtotal.'RY</td>';
echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
echo '</tr>';
$total = ($total + $subtotal); //add subtotal to total var
}

$result="insert into ordered (product_name,product_price) values ".implode(",",$queryData)) . ";";
if (mysqli_query($mysqli, $result)) {
echo "New record created successfully";
}

关于php - 如何在foreach中插入多条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55352356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com