diff --git a/shop-routes/product.js b/shop-routes/product.js index 92b65039a2b8049013dceb67194e3454c5bad823..05112684c70e02c5ca4e61371183221c3309338b 100644 --- a/shop-routes/product.js +++ b/shop-routes/product.js @@ -111,5 +111,21 @@ router.post("/edit/:id", upload.single("image"), async (req, res) => { } }); +// เธฅเธเธชเธดเธเธเนเธฒ +router.post("/delete/:id", async (req, res) => { + try { + const productId = req.params.id; + + // เธฅเธเธชเธดเธเธเนเธฒเธญเธญเธเธเธฒเธเธเธฒเธเธเนเธญเธกเธนเธฅ + await pool.execute("DELETE FROM products WHERE id = ?", [productId]); + + console.log("Product deleted successfully!"); + res.redirect("/products"); // เธเธฅเธฑเธเนเธเธขเธฑเธเธซเธเนเธฒเธฃเธฒเธขเธเธฒเธฃเธชเธดเธเธเนเธฒ + } catch (error) { + console.error("Error deleting product:", error); + res.status(500).send("Error deleting product."); + } +}); + module.exports = router; diff --git a/views/index.ejs b/views/index.ejs index ee1007c14feee226a30511fbaf8345e1f2b42010..ee37dee788f51bfb0b7f5ca125fecb24e04b8627 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -20,7 +20,13 @@ <button type="submit">Add to Cart</button> </form> <td> - <a href="/products/edit/<%= product.id %>">Edit</a> <!-- Edit button --> + <a href="/products/edit/<%= product.id %>">Edit</a> + + <form action="/products/delete/<%= product.id %>" method="POST" style="display: inline;"> + <button type="submit" onclick="return confirm('Are you sure you want to delete this product?')"> + Delete + </button> + </form> </td> </div> <% }); %> diff --git a/views/product.ejs b/views/product.ejs index 469296636f8341d2d3c77010f63a6571f5f43e14..01f834c0b0f4170901fe6d0f239c88fdfba344da 100644 --- a/views/product.ejs +++ b/views/product.ejs @@ -22,6 +22,13 @@ <td><%= product.price %> THB</td> <td><%= product.stock %></td> <td><%= product.description %></td> + <td> + <form action="/products/delete/<%= product.id %>" method="POST" style="display:inline;"> + <button type="submit" onclick="return confirm('Are you sure you want to delete this product?')"> + Delete + </button> + </form> + </td> </tr> <% }); %> </table>