我是新來的PHP。我正在做一個添加到購物車program.i列出幾個產品在一個頁面上,但我只能更改列表中的第一個產品的數量。而其他的則採用默認值1.我正在做一個添加到購物車程序。我列出幾個產品在一個page.but我只能改變數量的第一個產品
該程序用於在單個頁面上列出多個產品,從數據庫中檢索。有不同的類別,因此我從URL中獲取cat_id。
custproduct.php
<?php
session_start();
if (isset($_GET['id']))
{
// echo"id: ".$_GET['id'];
include ('custdb1.php');
echo "<h2>List of Products:</h2>";
$sql = "SELECT * FROM `product` WHERE `cat_id`=".$_GET['id'];
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Product ID: ". $row["pro_id"]. " - Product Name: ". $row["pro_name"]. "<br>";
echo "<img src='upload/".$row['pro_img']."'/>";
echo "<br> Price: Rs. ". $row["pro_price"]. " ";
echo "<br>";
echo "Quantity: <input type='text' name='qty' id='qty' value='1'>";
echo "<br>";
echo "<button onclick='addtocart(".$row['pro_id'].")'>Add To Cart</button>" ;
}
}
}
else {
echo "0 results";
}
?>
<script>
function addtocart(id)
{
var qty = document.getElementById('qty').value;
document.write("qty");
window.location ="cart.php?id="+id+"&qty="+qty;
}
</script>
這cart.php page.this頁面用於增加產品在cart.the客戶點擊下方「查看列表」
<?php
session_start();
include('custdb1.php');
//$id = isset($_GET['id']) ? $_GET['id'] : '';
if (isset($_GET['id']))
{
$id=$_REQUEST["id"];
$qty=$_REQUEST["qty"];
//echo"qty=".$qty;
$_SESSION['cart'][$id] = array('id'=> $id,'qty'=> $qty);
$sql = "SELECT `pro_img` FROM `product` WHERE `pro_id`=".$id;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "quantity:".$qty.'<br>';
echo "id:".$id.'<br>';
echo "<img src='upload/".$row['pro_img']."'/>";
}
}
}
echo "<h4 align='center'> click here to <a href='shoppingcart.php'>see list</a> </h4>";
echo "<h4 align='center'> click here to <a href='custprofile.php'>Continue Shopping</a> </h4>";
?>
這是鏈接看到他的車購物cart.php.this頁面顯示購物車中添加的產品...即客戶可以看到他的購物車。
<?php
session_start();
include('custdb1.php');
echo "<pre>";
$value=$_SESSION['cart'];
//print_r($value);
foreach ($value as $key=> $final_val){
$cat_id = $key;
$pro_id = $final_val['id'];
$qty = $final_val['qty'];
echo"product id:".$pro_id;
echo"quantity:".$qty;
$sql = "SELECT * FROM `product` WHERE `pro_id`=".$pro_id;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Product ID: ". $row["pro_id"]. " - Product Name: ". $row["pro_name"]. "<br>";
echo "<img src='upload/".$row['pro_img']."'/>";
// echo "<button onclick='update(".$row['pro_id'].")'>update</button>" ;
// echo "<h4 align='left'><a href='update.php'>update cart</a> </h4>";
}
}
else {
echo "0 results";
}
}
echo "<h4 align='center'> click here to <a href='custprofile.php'>Continue Shopping</a> </h4>";
?>
您的數量輸入類型html中不能有多個相同的ID。首先糾正該錯誤,然後告訴我們您的程序正在工作是否正確 – WebInsight
檢查我給出的解決方案,並嘗試它,並告訴我,如果它工作與否 – WebInsight