關於課程
menu.php
<a href=”product.php”>商品</a>
<a href=”favoriteshow.php”>我的最愛</a>
<a href=”history.php”>購買記錄</a>
<a href=”cartshow.php”>購物車</a>
<a href=”purchaseinput.php”>結帳</a>
<a href=”logininput.php”>登入</a>
<a href=”logoutinput.php”>登出</a>
<a href=”customerinput.php”>會員登錄</a>
<hr>
purchaseinput.php
<?php require ‘menu.php’; ?>
<?php
session_start();
if (!isset($_SESSION[‘customer’])) {
echo ‘請先登入再開始結帳。’;
} else
if (empty($_SESSION[‘product’])) {
echo ‘購物車內無商品。’;
} else {
echo ‘<p>姓名:’, $_SESSION[‘customer’][‘name’], ‘</p>’;
echo ‘<p>地址:’, $_SESSION[‘customer’][‘address’], ‘</p>’;
echo ‘<hr>’;
require ‘cart.php’;
echo ‘<hr>’;
echo ‘<p>請確認內容無誤後,按下確定購買開始結帳。</p>’;
echo ‘<a href=”purchaseoutput.php”>確定購買</a>’;
}
?>
purchaseoutput.php
<?php require ‘menu.php’; ?>
<?php
session_start();
$pdo=new PDO(‘mysql:host=localhost;dbname=shop;charset=utf8’,
‘root’, ‘12345678’);
$purchase_id=1;
foreach ($pdo->query(‘select max(id) from purchase’) as $row) {
$purchase_id=$row[‘max(id)’]+1;
}
$sql=$pdo->prepare(‘insert into purchase values(?,?)’);
if ($sql->execute([$purchase_id, $_SESSION[‘customer’][‘id’]])) {
foreach ($_SESSION[‘product’] as $product_id=>$product) {
$sql=$pdo->prepare(‘insert into purchase_detail values(?,?,?)’);
$sql->execute([$purchase_id, $product_id, $product[‘count’]]);
}
unset($_SESSION[‘product’]);
echo ‘已完成訂購,謝謝您的惠顧。’;
} else {
echo ‘很抱歉,結帳過程發生錯誤,無法完成訂購。’;
}
?>
history.php
<?php require ‘menu.php’; ?>
<?php
session_start();
if (isset($_SESSION[‘customer’])) {
$pdo=new PDO(‘mysql:host=localhost;dbname=shop;charset=utf8’,
‘root’, ‘12345678’);
$sql_purchase=$pdo->prepare(
‘select * from purchase where customer_id=? order by id desc’);
$sql_purchase->execute([$_SESSION[‘customer’][‘id’]]);
foreach ($sql_purchase->fetchAll() as $row_purchase) {
$sql_detail=$pdo->prepare(
‘select * from purchase_detail,product ‘.
‘where purchase_id=? and product_id=id’);
$sql_detail->execute([$row_purchase[‘id’]]);
echo ‘<table>’;
echo ‘<tr><th>商品編號</th><th>商品名稱</th>’,
‘<th>價格</th><th>數量</th><th>小計</th></tr>’;
$total=0;
foreach ($sql_detail->fetchAll() as $row_detail) {
echo ‘<tr>’;
echo ‘<td>’, $row_detail[‘id’], ‘</td>’;
echo ‘<td><a href=”detail.php?id=’, $row_detail[‘id’], ‘”>’,
$row_detail[‘name’], ‘</a></td>’;
echo ‘<td>’, $row_detail[‘price’], ‘</td>’;
echo ‘<td>’, $row_detail[‘count’], ‘</td>’;
$subtotal=$row_detail[‘price’]*$row_detail[‘count’];
$total+=$subtotal;
echo ‘<td>’, $subtotal, ‘</td>’;
echo ‘</tr>’;
}
echo ‘<tr><td>合計</td><td></td><td></td><td></td><td>’,
$total, ‘</td></tr>’;
echo ‘</table>’;
echo ‘<hr>’;
}
} else {
echo ‘請先登入,才能查詢購買記錄。’;
}
?>
Exercise Files