php
<?php
// listp.php
session_start();
$dbFile = __DIR__ . '/webdb.db';
try {
if (!file_exists($dbFile)) {
throw new Exception('Database file not found.');
}
$pdo = new PDO('sqlite:' . $dbFile);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 獲取分類
$stmt = $pdo->query('SELECT DISTINCT type FROM prod');
$categories = $stmt->fetchAll(PDO::FETCH_COLUMN);
// 獲取產品並加入評分
$stmt = $pdo->query('SELECT PID, pname, price, type FROM prod');
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
// 模擬產品評分和庫存數據
foreach ($products as &$product) {
$product['rating'] = rand(35, 50) / 10; // 3.5-5.0的隨機評分
$product['stock'] = rand(0, 100); // 0-100的隨機庫存
}
} catch (Exception $e) {
$error = $e->getMessage();
$products = [];
$categories = [];
}
// 模擬購物車數量
$cartCount = isset($_SESSION['cart']) ? count($_SESSION['cart']) : 0;
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>精選商品 | MyShop</title>
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@300;400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
:root {
--primary-color: #2196F3;
--secondary-color: #FFC107;
--accent-color: #FF5722;
--background-color: #f8f9fa;
--text-color: #333;
--card-shadow: 0 2px 8px rgba(0,0,0,0.1);
--header-height: 70px;
}
/* 原有的樣式保留,這裡添加新的樣式 */
.navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: var(--header-height);
background: white;
box-shadow: var(--card-shadow);
z-index: 1000;
display: flex;
align-items: center;
padding: 0 20px;
}
.navbar-brand {
font-size: 1.5em;
font-weight: bold;
color: var(--primary-color);
text-decoration: none;
}
.navbar-cart {
margin-left: auto;
position: relative;
}
.cart-icon {
font-size: 1.5em;
color: var(--text-color);
cursor: pointer;
}
.cart-count {
position: absolute;
top: -8px;
right: -8px;
background: var(--accent-color);
color: white;
border-radius: 50%;
width: 20px;
height: 20px;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8em;
}
.main-content {
margin-top: calc(var(--header-height) + 20px);
}
.product-card {
position: relative;
overflow: visible;
}
.product-badge {
position: absolute;
top: 10px;
right: 10px;
background: var(--accent-color);
color: white;
padding: 5px 10px;
border-radius: 15px;
font-size: 0.8em;
z-index: 1;
}
.product-rating {
display: flex;
align-items: center;
margin: 10px 0;
color: var(--secondary-color);
}
.product-rating .stars {
margin-right: 5px;
}
.product-stock {
font-size: 0.9em;
color: #666;
margin: 5px 0;
}
.stock-low {
color: var(--accent-color);
}
.add-to-cart {
width: 100%;
padding: 10px;
background: var(--primary-color);
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
margin-top: 10px;
}
.add-to-cart:hover {
background: #1976D2;
}
.add-to-cart:disabled {
background: #ccc;
cursor: not-allowed;
}
.sort-container {
margin: 20px 0;
display: flex;
justify-content: flex-end;
}
.sort-select {
padding: 8px;
border: 1px solid #ddd;
border-radius: 5px;
background: white;
}
.toast {
position: fixed;
bottom: 20px;
right: 20px;
background: rgba(0,0,0,0.8);
color: white;
padding: 15px 25px;
border-radius: 5px;
display: none;
animation: slideIn 0.3s ease;
}
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.loading-spinner {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.loading-spinner::after {
content: '';
width: 50px;
height: 50px;
border: 5px solid #f3f3f3;
border-top: 5px solid var(--primary-color);
border-radius: 50%;
animation: spin 1s linear infinite;
display: block;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* 響應式設計補充 */
@media (max-width: 768px) {
.navbar {
padding: 0 10px;
}
.search-container {
margin: 0 10px;
}
.sort-container {
justify-content: center;
}
}
</style>
</head>
<body>
<nav class="navbar">
<a href="#" class="navbar-brand">MyShop</a>
<div class="navbar-cart">
<i class="fas fa-shopping-cart cart-icon"></i>
<span class="cart-count"><?= $cartCount ?></span>
</div>
</nav>
<div class="main-content">
<div class="header">
<div class="container">
<h1>精選商品</h1>
<div class="search-container">
<input type="text" class="search-input" placeholder="搜尋商品..." id="searchInput">
</div>
</div>
</div>
<div class="container">
<div class="filters">
<button class="filter-btn active" data-type="all">全部商品</button>
<?php foreach ($categories as $category): ?>
<button class="filter-btn" data-type="<?= htmlspecialchars($category) ?>">
<?= htmlspecialchars($category) ?>
</button>
<?php endforeach; ?>
</div>
<div class="sort-container">
<select class="sort-select" id="sortSelect">
<option value="default">預設排序</option>
<option value="price-asc">價格由低到高</option>
<option value="price-desc">價格由高到低</option>
<option value="rating-desc">評分由高到低</option>
</select>
</div>
<?php if (isset($error)): ?>
<div class="no-results"><?= htmlspecialchars($error) ?></div>
<?php else: ?>
<div class="products-grid">
<?php foreach ($products as $product): ?>
<div class="product-card"
data-type="<?= htmlspecialchars($product['type']) ?>"
data-price="<?= $product['price'] ?>"
data-rating="<?= $product['rating'] ?>">
<?php if ($product['stock'] < 10): ?>
<div class="product-badge">庫存緊張</div>
<?php endif; ?>
<?php
$imgPath = htmlspecialchars($product['PID']) . '.jpg';
if (file_exists(__DIR__ . '/' . $imgPath)): ?>
<img class="product-image" src="<?= $imgPath ?>" alt="<?= htmlspecialchars($product['pname']) ?>">
<?php else: ?>
<div class="product-image">
<i class="fas fa-image" style="font-size: 48px; color: #ddd; display: flex; height: 100%; align-items: center; justify-content: center;"></i>
</div>
<?php endif; ?>
<div class="product-info">
<h3 class="product-name"><?= htmlspecialchars($product['pname']) ?></h3>
<div class="product-rating">
<div class="stars">
<?php
$rating = $product['rating'];
for ($i = 1; $i <= 5; $i++) {
if ($i <= $rating) {
echo '<i class="fas fa-star"></i>';
} elseif ($i - $rating < 1) {
echo '<i class="fas fa-star-half-alt"></i>';
} else {
echo '<i class="far fa-star"></i>';
}
}
?>
</div>
<span><?= number_format($rating, 1) ?></span>
</div>
<div class="product-price">NT$ <?= number_format($product['price']) ?></div>
<div class="product-stock <?= $product['stock'] < 10 ? 'stock-low' : '' ?>">
庫存: <?= $product['stock'] ?> 件
</div>
<span class="product-type"><?= htmlspecialchars($product['type']) ?></span>
<button class="add-to-cart"
<?= $product['stock'] == 0 ? 'disabled' : '' ?>
data-pid="<?= htmlspecialchars($product['PID']) ?>">
<?= $product['stock'] == 0 ? '已售完' : '加入購物車' ?>
</button>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
<div class="toast" id="toast"></div>
<div class="loading-spinner" id="loadingSpinner"></div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const searchInput = document.getElementById('searchInput');
const filterButtons = document.querySelectorAll('.filter-btn');
const sortSelect = document.getElementById('sortSelect');
const products = document.querySelectorAll('.product-card');
const toast = document.getElementById('toast');
const loadingSpinner = document.getElementById('loadingSpinner');
// 搜尋和過濾功能
function filterAndSortProducts() {
const searchTerm = searchInput.value.toLowerCase();
const activeType = document.querySelector('.filter-btn.active').dataset.type;
const sortValue = sortSelect.value;
// 轉換為陣列以便排序
let productsArray = Array.from(products);
// 排序
productsArray.sort((a, b) => {
switch(sortValue) {
case 'price-asc':
return parseFloat(a.dataset.price) - parseFloat(b.dataset.price);
case 'price-desc':
return parseFloat(b.dataset.price) - parseFloat(a.dataset.price);
case 'rating-desc':
return parseFloat(b.dataset.rating) - parseFloat(a.dataset.rating);
default:
return 0;
}
});
// 過濾和顯示
productsArray.forEach(product => {
const productName = product.querySelector('.product-name').textContent.toLowerCase();
const productType = product.dataset.type;
const matchesSearch = productName.includes(searchTerm);
const matchesType = activeType === 'all' || productType === activeType;
product.style.display = matchesSearch && matchesType ? 'block' : 'none';
});
// 重新排列DOM中的順序
const container = document.querySelector('.products-grid');
productsArray.forEach(product => {
container.appendChild(product);
});
// 檢查是否有顯示的商品
const hasVisibleProducts = productsArray.some(product =>
product.style.display === 'block'
);
// 更新無結果提示
let noResults = document.querySelector('.no-results');
if (!noResults) {
noResults = document.createElement('div');
noResults.className = 'no-results';
container.after(noResults);
}
if (!hasVisibleProducts) {
noResults.textContent = '找不到符合條件的商品';
noResults.style.display = 'block';
} else {
noResults.style.display = 'none';
}
}
// 事件監聽器
searchInput.addEventListener('input', filterAndSortProducts);
sortSelect.addEventListener('change', filterAndSortProducts);
filterButtons.forEach(button => {
button.addEventListener('click', function() {
filterButtons.forEach(btn => btn.classList.remove('active'));
this.classList.add('active');
filterAndSortProducts();
});
});
// 加入購物車功能
document.querySelectorAll('.add-to-cart').forEach(button => {
button.addEventListener('click', async function() {
const pi