加入收藏 | 设为首页 | 会员中心 | 我要投稿 云计算网_泰州站长网 (http://www.0523zz.com/)- 视觉智能、AI应用、CDN、行业物联网、智能数字人!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

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

发布时间:2021-02-25 08:02:49 所属栏目:MySql教程 来源:网络整理
导读:我试图在foreach循环中插入多个记录,这确实使我发疯,因为它只插入第一个记录然后停止.您能帮我知道我的问题在哪里吗? foreach ($_SESSION["cart_products"] as $cart_itm) { //set variables to use in content below $product_name = $cart_itm["product

我试图在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";
}

(编辑:云计算网_泰州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读