diff --git a/config/database.js b/config/database.js index 30e3a742829c20fa41e4daf46a927c4f51b31bdf..bb4c10f09741ed5171a092e396422874add51f12 100644 --- a/config/database.js +++ b/config/database.js @@ -22,4 +22,8 @@ const pool = mysql.createPool({ } })(); +pool.getConnection() + .then(() => console.log("Database connected!")) + .catch((err) => console.error("Database connection error:", err)); + module.exports = pool; \ No newline at end of file diff --git a/shop-routes/product.js b/shop-routes/product.js index b1ddf2017b1373cffb9a1527963b5227ec853cb4..bb5acd69543712729f1596e65ed090c2f0bcf2e3 100644 --- a/shop-routes/product.js +++ b/shop-routes/product.js @@ -42,25 +42,29 @@ router.get("/add", (req, res) => { // เน€เธเธดเนเธกเธชเธดเธเธเนเธฒเนเธซเธกเนเธเธฃเนเธญเธกเธฃเธนเธ router.post("/add", upload.single("image"), async (req, res) => { - console.log("Received Data:", req.body); // เน€เธเนเธเธเนเธฒเธ—เธตเนเธชเนเธเธกเธฒ - console.log("Uploaded file:", req.file); // เน€เธเนเธเธงเนเธฒ multer เนเธ”เนเนเธเธฅเนเนเธซเธก + console.log("req.file:", req.file); // เธ”เธนเธงเนเธฒ multer เนเธ”เนเธฃเธฑเธเนเธเธฅเนเนเธซเธก + console.log("req.body:", req.body); // เธ”เธนเธเนเธฒเธ—เธตเนเธชเนเธเธกเธฒเธเธฒเธเธเธญเธฃเนเธก try { const { name, price, stock, description } = req.body; - const priceNum = parseFloat(price); - const stockNum = parseInt(stock, 10); - if (isNaN(priceNum) || isNaN(stockNum)) { - return res.status(400).send("Price and stock must be valid numbers."); + if (!req.file) { + console.error("Error: No file uploaded!"); + return res.status(400).send("File upload failed"); } - // เธ–เนเธฒเนเธกเนเธกเธตเธเธฒเธฃเธญเธฑเธเนเธซเธฅเธ”เนเธเธฅเน เนเธซเน imagePath เน€เธเนเธ null - const imagePath = req.file ? "/uploads/" + req.file.filename : null; - - await pool.execute( - "INSERT INTO products (name, price, stock, description, image_url) VALUES (?, ?, ?, ?, ?)", - [name, priceNum, stockNum, description, imagePath] - ); + const imagePath = "/uploads/" + req.file.filename; + console.log("imagePath:", imagePath); // เธ•เธฃเธงเธเธชเธญเธเธเธฒเธเนเธเธฅเนเธฃเธนเธ + + try { + await pool.execute( + "INSERT INTO products (name, price, stock, description, image_url) VALUES (?, ?, ?, ?, ?)", + [name, price, stock, description, imagePath] + ); + } catch (error) { + console.error("Database Error:", error); + return res.status(500).json({ error: "Database Error", details: error }); + } res.redirect("/products"); } catch (error) {