如何在MYSQL表中存储购物车内容(foreach?)

时间:2017-09-15 14:23:27

标签: php mysql foreach cart

我有一个工作车(见下面的代码)但现在我想将内容存储在'订单' MYSQL表,在' dbexample'数据库。 添加到' order_number'和' order_status'领域。 这样我就可以建立订单跟踪/状态系统。

我的购物车看起来像这样: (使用"立即购买"我想打开place-order.php。代码应该去的地方。)

<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<h1 align="center">View Cart</h1>
<div class="cart-view-table-back">
<form method="post" action="cart_update.php">
<table width="100%"  cellpadding="6" cellspacing="0"><thead><tr><th>Quantity</th><th>Name</th><th>Price</th><th>Total</th><th>Remove</th></tr></thead>
  <tbody>
    <?php
    if(isset($_SESSION["cart_products"])) //check session var
    {
        $total = 0; //set initial total value
        $b = 0; //var for zebra stripe table 
        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

            $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>'.$currency.$product_price.'</td>';
            echo '<td>'.$currency.$subtotal.'</td>';
            echo '<td><input type="checkbox" name="remove_code[]" value="'.$product_code.'" /></td>';
            echo '</tr>';
            $total = ($total + $subtotal); //add subtotal to total var
        }

        $grand_total = $total + $shipping_cost; //grand total including shipping cost
        foreach($taxes as $key => $value){ //list and calculate all taxes in array
                $tax_amount     = round($total * ($value / 100));
                $tax_item[$key] = $tax_amount;
                $grand_total    = $grand_total + $tax_amount;  //add tax val to grand total
        }

        $list_tax       = '';
        foreach($tax_item as $key => $value){ //List all taxes
            $list_tax .= $key. ' : '. $currency. sprintf("%01.2f", $value).'<br />';
        }
        $shipping_cost = ($shipping_cost)?'Shipping Cost : '.$currency. sprintf("%01.2f", $shipping_cost).'<br />':'';
    }
    ?>
    <tr><td colspan="5"><span style="float:right;text-align: right;"><?php echo $shipping_cost. $list_tax; ?>Amount Payable : <?php echo sprintf("%01.2f", $grand_total);?></span></td></tr>
    <tr><td colspan="5"><a href="index.php" class="button">Add More Items</a><button type="submit">Update</button></td></tr>
    <a href="place-order.php" ><img src="images/buynow.jpg" width="179"
  </tbody>
</table>
<input type="hidden" name="return_url" value="<?php 
$current_url = urlencode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
echo $current_url; ?>" />
</form>
</div>

</body>
</html>

作为测试我复制了这个页面,称之为place-order.php并且只添加了:

$sql = "INSERT INTO orders (product_code, product_name, product_price, product_qty)
VALUES ('$product_code', '$product_name', '$product_price', '$product_qty' )";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

这也有效,但只有一个产品被添加到&#39;订单&#39;表。 我怀疑它应该用&#34;为每个&#34;或者其他的东西 ?尝试了很多,但无法让它发挥作用。 谁可以指出我正确的方向?

1 个答案:

答案 0 :(得分:0)

使用您的语法,您实际上可以像这样插入多行。

INSERT INTO tableName
    (column1, column2, column3, column4)
VALUES
    ('value1', 'value2', 'value3', 'value4'),
    ('value1', 'value2', 'value3', 'value4'),
    ('value1', 'value2', 'value3', 'value4');

您可以在现有的foreach循环中执行此操作,在此循环中计算小计和总计。

请注意,在SQL查询中使用没有清理的变量会导致严重的安全问题。您可以使用例如mysqli或PDO的准备查询来保护自己。你可以在这里阅读更多相关信息:

How can I prevent SQL injection in PHP?

http://php.net/manual/en/book.pdo.php

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php