關於課程
cartinsert.php
<?php
session_start();
$id=$_REQUEST[‘id’];
if (!isset($_SESSION[‘product’])) {
$_SESSION[‘product’]=[];
}
$count=0;
if (isset($_SESSION[‘product’][$id])) {
$count=$_SESSION[‘product’][$id][‘count’];
}
$_SESSION[‘product’][$id]=[
‘name’=>$_REQUEST[‘name’],
‘price’=>$_REQUEST[‘price’],
‘count’=>$count+$_REQUEST[‘count’]
];
echo ‘<p>商品放入購物車成功。</p>’;
echo ‘<hr>’;
require ‘cart.php’;
?>
cart.php
<?php
if (!empty($_SESSION[‘product’])) {
echo ‘<table>’;
echo ‘<th>商品編號</th><th>商品名稱</th>’;
echo ‘<th>價格</th><th>數量</th><th>小計</th>’;
$total=0;
foreach ($_SESSION[‘product’] as $id=>$product) {
echo ‘<tr>’;
echo ‘<td>’, $id, ‘</td>’;
echo ‘<td><a href=”detail.php?id=’, $id, ‘”>’,
$product[‘name’], ‘</a></td>’;
echo ‘<td>’, $product[‘price’], ‘</td>’;
echo ‘<td>’, $product[‘count’], ‘</td>’;
$subtotal=$product[‘price’]*$product[‘count’];
$total+=$subtotal;
echo ‘<td>’, $subtotal, ‘</td>’;
echo ‘<td><a href=”cartdelete.php?id=’, $id, ‘”>刪除</a></td>’;
echo ‘</tr>’;
}
echo ‘<tr><td>合計</td><td></td><td></td><td></td><td>’, $total,
‘</td><td></td></tr>’;
echo ‘</table>’;
} else {
echo ‘購物車內無商品。’;
}
?>
cartdelete.php
<?php
session_start();
unset($_SESSION[‘product’][$_REQUEST[‘id’]]);
echo ‘所選商品已移出購物車。’;
echo ‘<hr>’;
require ‘cart.php’;
?>