Gitlab@Informatics

Skip to content
Snippets Groups Projects
Select Git revision
  • 0497f4dbea6b3003e337c5911de26f1fbd7d489d
  • main default protected
  • revert-a98119d8
3 results

Readme.md

  • supplierController.js 4.21 KiB
    const db = require('../config/db');  // เชื่อมต่อกับฐานข้อมูล
    
    // ฟังก์ชันแสดงฟอร์มการเพิ่มผู้จัดจำหน่าย
    exports.createSupplierForm = (req, res) => {
      res.render('create-supplier', {
        title: 'Create New Supplier',
      });
    };
    
    
    // ฟังก์ชันบันทึกข้อมูลผู้จัดจำหน่ายใหม่
    exports.createSupplier = (req, res) => {
      const { name, address, phone, email } = req.body;  // รับข้อมูลจากฟอร์ม
    
      // ตรวจสอบข้อมูล
      if (!name || !address || !phone || !email) {
        return res.status(400).send('All fields are required');
      }
    
      // คำสั่ง SQL สำหรับเพิ่มข้อมูลผู้จัดจำหน่าย
      const query = 'INSERT INTO suppliers (name, address, phone, email) VALUES (?, ?, ?, ?)';
    
      // ใช้ mysql2 เพื่อบันทึกข้อมูล
      db.execute(query, [name, address, phone, email])
        .then(([results, fields]) => {
          res.redirect('/supplier-list');  // ไปที่หน้ารายการผู้จัดจำหน่าย
        })
        .catch((err) => {
          console.error(err);
          res.status(500).send('Error creating supplier');
        });
    };
    
    // ฟังก์ชันเพื่อดึงข้อมูลผู้จัดจำหน่ายทั้งหมดจากฐานข้อมูล
    exports.getSupplierList = (req, res) => {
      const query = 'SELECT * FROM suppliers';
    
      db.execute(query)
        .then(([suppliers, fields]) => {
          res.render('supplier-list', {
            title: 'Supplier List',
            suppliers: suppliers,
          });
        })
        .catch((err) => {
          console.error(err);
          res.status(500).send('Error retrieving suppliers');
        });
    };
    
    // ฟังก์ชันแสดงฟอร์มการแก้ไข
    exports.editSupplierForm = (req, res) => {
      const supplierId = req.params.id;
    
      // คำสั่ง SQL เพื่อดึงข้อมูลผู้จัดจำหน่ายตาม ID
      const query = 'SELECT * FROM suppliers WHERE id = ?';
    
      db.execute(query, [supplierId])
        .then(([rows, fields]) => {
          if (rows.length === 0) {
            return res.status(404).send('Supplier not found');
          }
          res.render('edit-supplier', {
            title: 'Edit Supplier',
            supplier: rows[0],  // ส่งข้อมูลผู้จัดจำหน่ายไปยังหน้า
          });
        })
        .catch((err) => {
          console.error(err);
          res.status(500).send('Error retrieving supplier');