我正在做一個HTML,CSS,PHP和MySQL的項目。該項目是一個網上蔬菜店,幾乎是一個電子商務網站。我需要使用PHP將數據從HTML表格(我的購物車)存儲到MySQL數據庫。該表是這樣的: http://i.imgur.com/OngFBuP.png我需要將數據從HTML表格存儲到MySQL數據庫使用PHP
的「購物車」的代碼是:
'<?php
include("session.php");
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="buy.php">
<table id="myTable" width="100%" cellpadding="6" cellspacing="0"> <thead><tr><th>Sl_no</th><th>Username</th><th>Quantity</th><th>Name</th> <th>Price</th><th>Total</th><th>Remove</th></tr></thead>
<tbody>
<?php
if(isset($_SESSION["cart_products"]))
{
$total = 0;
$fl=1;
$b = 0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$subtotal = ($product_price * $product_qty);
$bg_color = ($b++%2==1) ? 'odd' : 'even';
echo '<tr class="'.$bg_color.'">';
echo '<td>'.$fl.'</td>';
echo '<td>'.$user.'</td>';
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.'</td>';
echo '<td>'.$subtotal.'</td>';
echo '<td><input type="checkbox" name="remove_code[]"
value="'.$product_code.'" /></td>';
echo '</tr>';
$fl++;
$total = ($total + $subtotal);
}
echo$fl;
$grand_total = $total;
}
?>
</tbody>
</table>
<button name="btn1" type="submit">buy</button>
<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>'
,我使用一個PHP頁面(buy.php
)存儲在數據庫中的所有數據。爲buy.php
的代碼是:
'<?php
include('session.php');
$con=new mysqli("localhost","root","","test");
$total=0;
foreach ($_SESSION["cart_products"] as $cart_itm)
{
$product_name = $cart_itm["product_name"];
$product_qty = $cart_itm["product_qty"];
$product_price = $cart_itm["product_price"];
$product_code = $cart_itm["product_code"];
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$sql="INSERT INTO cart (Uname,TotalCost,veg_id,quantity)
VALUES('$user','$total','$product_code','$product_qty')";
if($con->query($sql)==true){
echo"data inserted successfully";
}
echo"<br><br><a href='index_2.php'> Return to Your Dashboard</a>
<a href='buy_veg.php'> Buy More Items</a>";
?>'
的問題是,這buy.php
頁面實際上是存儲的最後一條記錄到數據庫中。圖片鏈接: http://i.imgur.com/ZaCnvjI.png
我想將所有購物車項目存儲到數據庫。我需要做些什麼來解決這個問題?
你需要在每次迭代中插入值,所以只要將查詢執行部分進入的foreach內 – JYoThI