Gitlab@Informatics

Skip to content
Snippets Groups Projects
Commit 2873a823 authored by 65160270's avatar 65160270
Browse files

update-edit

parent 94644f99
Branches
No related tags found
No related merge requests found
......@@ -443,6 +443,7 @@ footer {
text-decoration: none;
border-radius: 5px;
border: 1px solid #ffc107;
cursor: pointer;
}
.edit-btn:hover {
......
......@@ -127,4 +127,10 @@ router.post('/remove', async (req, res) => {
}
});
router.post('/edit', (req, res) => {
const { cartItemId } = req.body;
req.session.editingItemId = cartItemId; // เก็บ ID ไว้ชั่วคราว
res.redirect('/'); // กลับไปเลือกสินค้าใหม่
});
module.exports = router;
\ No newline at end of file
require('dotenv').config(); //โหลดตัวแปร .env ก่อน
require('dotenv').config();
const express = require('express');
const router = express.Router();
const pool = require('../config/database'); //Import database หลังจากโหลด .env
const isLoggedIn = (req, res, next) => {
if (req.session.userId) {
next(); // ผู้ใช้ Login แล้ว
} else {
res.redirect('/login'); // ยังไม่ Login
}
};
const pool = require('../config/database');
console.log("Database Host:", process.env.DB_HOST);
// แสดงสินค้าในหน้าแรก
router.get('/', async (req, res) => {
try {
const [products] = await pool.query('SELECT * FROM products WHERE stock > 0');
......@@ -22,4 +16,45 @@ router.get('/', async (req, res) => {
}
});
// เพิ่มสินค้าในตะกร้า (รองรับระบบ Edit)
router.post('/add-to-cart', async (req, res) => {
const { productId, quantity } = req.body;
try {
const [productResult] = await pool.query('SELECT * FROM products WHERE id = ? AND stock > 0', [productId]);
if (productResult.length === 0) {
return res.status(404).send('Product not found or out of stock');
}
const product = productResult[0];
if (!req.session.cart) {
req.session.cart = [];
}
// ถ้ากำลังแก้ไขสินค้า
if (req.session.editingItemId) {
req.session.cart = req.session.cart.map(item =>
item.id === parseInt(req.session.editingItemId)
? { id: product.id, name: product.name, price: product.price, quantity: parseInt(quantity), stock: product.stock }
: item
);
req.session.editingItemId = null; // ล้างค่า
} else {
// เพิ่มสินค้าปกติ
req.session.cart.push({
id: product.id,
name: product.name,
price: product.price,
quantity: parseInt(quantity),
stock: product.stock
});
}
res.redirect('/cart'); // กลับไปหน้าตะกร้า
} catch (error) {
console.error(error);
res.status(500).send('Error adding product to cart');
}
});
module.exports = router;
\ No newline at end of file
......@@ -41,7 +41,12 @@
Remove
</button>
</form>
<a href="/" class="Edit-btn">Edit</a> <!-- ปุ่ม Edit -->
<form action="/cart/edit" method="POST">
<input type="hidden" name="cartItemId" value="<%= item.id %>">
<button type="submit" class="edit-btn">
Edit
</button>
</form>
</div>
<% }); %>
</div>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment