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

php-如何在foreach中插入多个记录,第1张

概述我试图在foreach循环中插入多个记录,这确实使我发疯,因为它只插入第一个记录然后停止.您能帮我知道我的问题在哪里吗?foreach ($_SESSION['cart_products'] as $cart_itm) { //set variables to use in content below $product_name = $ca

我试图在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 >';    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 >';    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中插入多个记录 全部内容,希望文章能够帮你解决php-如何在foreach中插入多个记录 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/sjk/1166043.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存