问题
<?php
session_start();
print '<h1>Your Shopping Cart:</h1>';
print '<h4>The Product ID: '.$_SESSION['id'].' </h4>';
print '<h4>The Quantity: '.$_SESSION['quantity'].' </h4>';
$dbc = mysql_connect('127.0.0.1', 'root', '');
mysql_select_db('product', $dbc);
$query = "SELECT * FROM prod WHERE id='".$_SESSION['id']."'";
if ($r = mysql_query($query, $dbc)) {
while ($row = mysql_fetch_array($r)) {
print "<p><b>Product Name: {$row['name']}<br />
The Price: {$row['price']}<br />
Shipping Cost: {$row['shipping']}<br />
</p><hr />\n";
}}
?>
This code for shopping cart with Session but the problem is that it keeps only one product.
For example, if you purchase a product A and in Cart product B delete B then add A product Please help me I want to add more than one product and printed on the screen ##
回答1:
Add another level to your cart:
$_SESSION['cart'][$productID]['quantity'];
^^^^^^^^^^^^^
so you keep per-product data. Right now you're using a single level that you're continually overwriting as new products are added.
回答2:
Say hello to php arrays: http://www.php.net/manual/en/book.array.php :)
Basically instead of :
$_SESSION['id'] = 1234;
You will want:
$_SESSION['products'][] = array('id'=>1234, 'quantity'=>10);
Then you will iterate over $_SESSION['products'] like
foreach($_SESSION['products'] AS $product){
echo $product['id'];
}
回答3:
You should maintain your cart in single session variable $_SESSION['cart']
. When adding new products you can use this,
$_SESSION['cart'] = array(); //initialize once
array_push($_SESSION['cart'], array("id" => $id, "quantity" => $q));
print_r($_SESSION['cart']);
This way, you can have multiple products in cart.
For specific framework, CodeIgniter, there's a class which provides cart functionality. Check this out.
回答4:
$_SESSION['cart'] = array();
$_SESSION['cart']['1'] = 2;//add product A,id=1,quality=2
$_SESSION['cart']['2'] = 3;//add product B,id=2,quality=3
//get all items
foreach($_SESSION['cart'] as $item)
{
print_r($item);
}
来源:https://stackoverflow.com/questions/15979952/shopping-cart-session-php