Example : Node Js code for Save, Reset, Update, Delete, and Fetch & Fill in Single Integrated Form.

student.css ( inside 'css' sub-folder in 'public' folder )


 * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(to right, #74ebd5, #9face6);
            font-family: 'Poppins', sans-serif;
            margin: 0;
            padding: 0;
        }

        .form-container {
            background: #ffffff;
            max-width: 800px;
            margin: 50px auto;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease-in-out;
        }

        .form-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
        }

        h1 {
            text-align: center;
            margin-bottom: 35px;
            font-weight: 600;
            color: #4e54c8;
        }

        h3 {
            text-align: center;
            margin-top: 20px;
            margin-bottom: 50x;
            text-decoration: underline;
            color: #3f4246;

        }

        a {
            margin-top: 5px;
            margin: 0 5px;
            text-decoration: none;
            color: #007bff;
        }

        a:hover {
            text-decoration: underline;
        }

        label {
            display: block;
            margin-top: 15px;
            font-weight: bold;
            font-weight: 500;
            margin-bottom: 8px;
            color: #333;
            font-size: medium;
        }

        .form-group {
            margin-bottom: 10px;
            display: flex;
            gap: 30px;
            margin-top: 10px;
        }

        .form-group>div {
            flex: 1;
        }

        input[type="text"],
        input[type="email"],
        input[type="number"],
        input[type="date"],
        input[type="file"],
        textarea {
            width: 100%;
            padding: 8px;
            margin-top: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        textarea {
            resize: vertical;
        }

        .form-group input[type="text"],
        .form-group input[type="date"],
        .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 8px;
            outline: none;
            transition: 0.3s;
        }

        .form-group input[type="text"]:focus,
        .form-group input[type="date"]:focus,
        .form-group select:focus {
            border-color: #6a82fb;
            box-shadow: 0 0 8px rgba(106, 130, 251, 0.4);
        }

        .form-group input[type="radio"],
        .form-group input[type="checkbox"] {
            margin-right: 8px;
        }

        .checkbox-group,
        .form-group>div {
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
        }

        .form-group input[type="file"] {
            padding: 10px;
        }


        .buttons {
            margin-top: 25px;
            display: flex;
            gap: 10px;
            justify-content: space-between;
        }

        button {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
        }

        .submit-btn {
            background-color: #28a745;
            color: white;
        }

        .update-btn {
            background-color: #ffc107;
            color: white;
        }

        .delete-btn {
            background-color: #dc3545;
            color: white;
        }

        .reset-btn {
            background-color: #17a2b8;
            color: white;
        }

        .exit-btn {
            background-color: #6c757d;
            color: white;
        }

        .submit-btn:hover,
        .update-btn:hover,
        .delete-btn:hover,
        .reset-btn:hover,
        .exit-btn:hover {
            opacity: 0.9;
        }


===============================================================================

studentModule.ejs (inside 'views' folder)

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Student Module</title>

    <link rel="stylesheet" href="/css/student.css">

    <script>
        function resetForm() {
            const form = document.getElementById("studentForm");
            form.reset();
            form.querySelectorAll("input,textarea,select").forEach(e1 => {
                if (e1.type === "checkbox" || e1.type === "radio") {
                    e1.checked = false;
                } else {
                    e1.value = "";
                }
            });
        }
    </script>
</head>

<body>
    <div class="form-container">

        <h1>Student Module</h1>

        <% if(message){%>
            <p style="color: green;">
                <%=message%>
            </p>
            <% }%>

                <!-- Email dropdown to fetch student -->
                <form action="/studentModule" method="get">

                    <select name="search2" onchange="this.form.submit()">
                        <option value="">Choose Student Email</option>
                        <% emails.forEach(function(email){ %>
                            <option value="<%=email%>" <%=studentModule2.email5===email ? "selected" : "" %>>
                                <%=email%>
                            </option>

                            <%});%>
                    </select>
                </form>

                <!-- <form action="/studentModule" method="POST" id="studentForm" enctype="multipart/form-data" onsubmit="return validateDOB()"> -->
                <form action="/studentModule" method="POST" id="studentForm" onsubmit="return validateDOB()">

                    <div class="form-header">
                        <span>Serial No:<strong>001</strong></span>
                        <span class="form-group"> <label>Date:</label><input type="date" id="date" name="date1"
                                value="<%= studentModule2.date5 || '' %>" required
                                title="Select your date of birth (You must be at least 18 years old)."></span>
                    </div>

                    <!-- Student Name -->
                    <label for="name">Student Full Name:</label>
                    <input type="text" id="name" name="name1" placeholder="Enter full name"
                        value="<%= studentModule2.name5 || '' %>" required maxlength="100" pattern="[A-Za-z\s]+"
                        title="Only letters and spaces allowed and of max 100 characters.">

                    <!-- Student Fee -->
                    <label> Student Fee Amount </label>
                    <input type="text" id="fee" name="fee1" placeholder="Enter fee amount"
                        value="<%= studentModule2.fee5 || '' %>">


                    <!-- Student Gender -->

                    <div class="form-group">
                        <label>Student Gender:</label>
                        <label><input type="radio" name="gen1" value="Male" <%=studentModule2.gen5=="Male" ? "checked"
                                : "" %> required> Male </label>
                        <label><input type="radio" name="gen1" value="Female" <%=studentModule2.gen5=="Female"
                                ? "checked" : "" %>required> Female</label>
                        <label><input type="radio" name="gen1" value="Transgender" <%=studentModule2.gen5=="Transgender"
                                ? "checked" : "" %> required> Transgender</label>
                    </div>

                    <!-- Student father and mother name -->
                    <div class="form-group">
                        <div>
                            <label>Student Father's Name:</label>
                            <input type="text" id="fname" name="fname1" placeholder="Enter father's name"
                                value="<%= studentModule2.fname5 || '' %>" required maxlength="100"
                                pattern="[A-Za-z\s]+"
                                title="Only letters and spaces allowed and of max 100 characters.">
                        </div>
                        <div>
                            <label>Student Mother's Name:</label>
                            <input type="text" id="mother-name" name="mname1" placeholder="Enter mother's name"
                                value="<%= studentModule2.mname5 || '' %>" required maxlength="100"
                                pattern="[A-Za-z\s]+"
                                title="Only letters and spaces allowed and of max 100 characters.">
                        </div>
                    </div>

                    <!-- Student email and aadhar -->
                    <div class="form-group">
                        <div>
                            <label>Student Email ID:</label>
                            <input type="email" id="email2" name="email1" placeholder="Enter email id"
                                value="<%= studentModule2.email5 || '' %>" required
                                title="Enter a valid email (as e.g., [email protected])">
                        </div>
                        <div>
                            <label>Student Aadhar NUmber:</label>
                            <input type="number" id="adhar2" name="aadhar1" placeholder="Enter aadhar number"
                                value="<%= studentModule2.aadhar5 || '' %>">
                        </div>
                    </div>

                    <!-- Student roll and dob -->
                    <div class="form-group">
                        <div>
                            <label>Student Roll:</label>
                            <input type="number" id="roll2" name="roll1" placeholder="Enter roll number"
                                value="<%= studentModule2.roll5 || '' %>">
                        </div>
                        <div>
                            <label> Student Date of Birth:</label>
                            <input type="date" id="dob2" name="dob1" placeholder="Enter your dob"
                                value="<%= studentModule2.dob5 || '' %>" required
                                title="Select your date of birth (You must be at least 18 years old).">
                        </div>
                    </div>

                    <!-- Student mobile and whatshapp number -->
                    <div class="form-group">
                        <div>
                            <label>Student Mobile No:</label>
                            <input type="number" id="mobile" name="mob1" placeholder="Enter mobile number"
                                value="<%= studentModule2.mob5 || '' %>" required pattern="^(\+91|91)\d{10}$"
                                title="Please enter a valid 10-digit phone number.">
                        </div>
                        <div>
                            <label>Student WhatsApp No:</label>
                            <input type="number" id="whatsapp" name="whats1" placeholder="Enter WhatsApp number"
                                value="<%= studentModule2.whats5 || '' %>" required pattern="^\d{10}$"
                                title="Please enter a valid 10-digit phone number.">
                        </div>
                    </div>

                    <!-- Student Course and Course Duration -->
                    <div class="form-group">
                        <div>
                            <label> Student Course:</label>
                            <input type="text" id="course" name="cou1" placeholder="Enter course name"
                                value="<%= studentModule2.cou5 || '' %>">
                        </div>
                        <div>
                            <label> Student Course Duration:</label>
                            <input type="text" id="course-duration" name="coudur1" placeholder="like4 Years"
                                value="<%= studentModule2.coudur5 || '' %>">
                        </div>
                    </div>

                    <!-- Student city ,state,nationality -->
                    <div class="form-group">
                        <div>
                            <label>Student City:</label>
                            <input type="text" id="city" name="city1" placeholder="Enter city"
                                value="<%= studentModule2.city5 || '' %>">
                        </div>
                        <div>
                            <label>Student State:</label>
                            <input type="text" id="state" name="state1" placeholder="Enter state"
                                value="<%= studentModule2.state5 || '' %>">
                        </div>
                        <div>
                            <label>Student Nationality:</label>
                            <input type="text" id="nationality" name="nat1" placeholder="Enter nationality"
                                value="<%= studentModule2.nat5 || '' %>">
                        </div>
                    </div>

                    <!-- Student Address -->
                    <label>Student Address:</label>
                    <textarea id="address" rows="3" cols="30" name="add1" maxlength="500" required placeholder="Enter a short bio (max 500 characters)."><%= studentModule2.add5 || '' %></textarea>

                    <!-- <label> Student Upload Photo:</label>
                    <input type="file" id="img2" name="img1" placeholder="Uploady your photo"
                        accept=".jpg, .jpeg, .png, .gif" required
                        title="Upload an image file (.jpg, .jpeg, .png, .gif)."> -->

                    <div class="buttons">
                        <button type="submit" class="submit-btn" name="btn" value="save">Submit</button>
                        <button type="button" class="reset-btn" onclick="resetForm()">Reset</button>
                        <button type="submit" class="update-btn" name="btn" value="update">Update</button>
                        <button type="submit" class="delete-btn" name="btn" value="delete"
                            onclick="return confirm('Are you sure to delete?')">Delete</button>
                    </div>
                </form>


    </div>
    <script>
        // This script calculates the maximum acceptable date for the DOB field to ensure that 
        // the user is at least 18 years old.
        window.onload = function () {
            var today = new Date();
            today.setFullYear(today.getFullYear() - 18);
            var dd = today.getDate();
            var mm = today.getMonth() + 1; //January is 0!
            var yyyy = today.getFullYear();
            if (dd < 10) {
                dd = "0" + dd;
            }

            if (mm < 10) {
                mm = "0" + mm;
            }
            // Set max attribute for DOB so that the user is at least 18 years old.
            document.getElementById("dob2").max = yyyy + "-" + mm + "-" + dd;
        };

        // Additional check (in case the browser doesn't honor the max attribute) 
        // to prevent submission if the DOB is later than allowed.
        function validateDOB() {
            var dobField = document.getElementById("dob2");
            var dob = new Date(dobField.value);
            var maxDOB = new Date(dobField.max);
            if (dob > maxDOB) {
                alert("You must be at least 18 years old.");
                return false;
            }
            return true;
        }
    </script>


    </form>

</body>

</html>

===============================================================================

Server.js


const express = require("express");
const session = require('express-session');
const mysql = require("mysql");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();
const PORT = 3000;


// Middleware
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

// Initialize session middleware
app.use(session({
    secret: "mySecretKey",  // Secret key for signing session ID
    resave: false,          // Avoid resaving unchanged sessions
    saveUninitialized: true // Save new sessions
}));

//📌 MySQL Database Connection
const db = mysql.createConnection({
    host: "localhost",
    user: "root", // Default XAMPP MySQL username
    password: "", // Default is empty in XAMPP
    database: "ohms"
});

db.connect((err) => {
    if (err) {
        console.error("❌ Database Connection Failed!", err);
        return;
    }
    console.log("✅ Connected to MySQL Database");
});

// -----------------   STUDENT MODULE    --------------------



function getAllEmails(callback) {
    db.query("SELECT DISTINCT email5 FROM student", (err, results) => {
        if (err) return callback(err);
        const emails = results.map(row => row.email5);
        callback(null, emails);
    });
}

app.get("/studentModule", (req, res) => {
    const selectedEmail = req.query.search2 || "";
    const message = req.query.message || "";

    getAllEmails((err, emails) => {
        if (err) {
            console.error("Email fetch error:", err);
            return res.render("studentModule", { title: "student form", emails: [], studentModule2: {}, message: "Error loading emails" });
        }

        if (selectedEmail) {
            db.query("SELECT * FROM student WHERE email5 = ?", [selectedEmail], (err, results) => {
                if (err) {
                    console.error("Email fetch error:", err);
                    return res.render("studentModule", { title: "student form", emails, studentModule2: {}, message: "Error fetching student" });
                }
                res.render("studentModule", {
                    title: "student form",
                    emails,
                    studentModule2: results[0] || {},
                    message: results.length ? message : "Student not found"
                });
            });
        } else {
            res.render("studentModule", { title: "Student form", emails, studentModule2: {}, message });
        }
    });
});

// ====================NEW CODE======================

// POST route to handle Save, Update, and Delete
app.post("/studentModule", (req, res) => {
    const action = req.body.btn;
    const data = req.body;

    if (action === "save") {
        // Check if email already exists
        db.query("SELECT * FROM student WHERE email5 = ?", [data.email1], (err, results) => {
            if (err) {
                console.error("Check email error:", err);
                return res.redirect("/studentModule?message=Error checking existing email");
            }

            if (results.length > 0) {
                return res.redirect("/studentModule?message=Email already exists");
            }

            // Insert new record
            const insertQuery = ` INSERT INTO student (date5,name5,gen5,fee5,fname5,mname5,email5,aadhar5,roll5,dob5,mob5,whats5,cou5,coudur5,city5,state5,nat5,add5)
            VALUES (?, ?, ?, ?, ?, ?,?,?,?,?, ?, ?, ?, ?, ?, ?,?,?)`;

            const values = [
                data.date1, data.name1, data.gen1, data.fee1, data.fname1, data.mname1, data.email1, data.aadhar1, data.roll1, data.dob1, data.mob1, data.whats1, data.cou1, data.coudur1, data.city1, data.state1, data.nat1, data.add1

            ];

            db.query(insertQuery, values, err => {
                if (err) {
                    console.error("Insert error:", err);
                    return res.redirect("/studentModule?message=Error saving data");
                }
                res.redirect("/studentModule?message=Data Saved Successfully");
            });
        });

    } else if (action === "update") {
        console.log("update successfully")
        const updateQuery = `UPDATE student SET  date5=?,name5=?,gen5=?,fee5=?,fname5=?,mname5=?,aadhar5=?,roll5=?,dob5=?,mob5=?,whats5=?,cou5=?,coudur5=?,city5=?,state5=?,nat5=?,add5=? where email5=?`;

        const values = [
            data.date1, data.name1, data.gen1, data.fee1, data.fname1, data.mname1, data.aadhar1, data.roll1, data.dob1, data.mob1, data.whats1, data.cou1, data.coudur1, data.city1, data.state1, data.nat1, data.add1, data.email13

        ];

        db.query(updateQuery, values, (err, result) => {
            if (err) {
                console.error("Update error:", err);
                return res.redirect("/studentModule?message=Error updating data");
            }
            if (result.affectedRows === 0) {
                return res.redirect("/studentModule?message=No record found to update");
            }
            res.redirect("/studentModule?message=Data Updated Successfully");
        });

    } else if (action === "delete") {
        console.log("Hello");
        const deleteQuery = "DELETE FROM student WHERE email5 = ?";

        db.query(deleteQuery, [data.email1], (err, result) => {
            if (err) {
                console.error("Delete error:", err);
                return res.redirect("/studentModule?message=Error deleting data");
            }
            if (result.affectedRows === 0) {
                return res.redirect("/studentModule?message=No record found to delete");
            }
            res.redirect("/studentModule?message=Data Deleted Successfully");
        });

    } else {
        res.redirect("/studentModule?message=Invalid action");
    }
});




// 📌 Start the Server

app.listen(PORT, () => {
    console.log(`🚀 Server running at http://localhost:${PORT}`);
});

================================================================================

Xampp MySQL database= ohms and Table= student		

DESCRIBE student;

date5	varchar(20)	YES		NULL		
name5	varchar(20)	YES		NULL		
gen5	varchar(10)	YES		NULL		
fee5	float	YES		NULL		
fname5	varchar(20)	YES		NULL		
mname5	varchar(20)	YES		NULL		
email5	varchar(20)	YES	UNI	NULL		
aadhar5	bigint(20)	YES		NULL		
roll5	int(10)	YES		NULL		
dob5	varchar(10)	YES		NULL		
mob5	bigint(15)	YES		NULL		
whats5	bigint(15)	YES		NULL		
cou5	varchar(10)	YES		NULL		
coudur5	varchar(10)	YES		NULL		
city5	varchar(10)	YES		NULL		
state5	varchar(10)	YES		NULL		
nat5	varchar(15)	YES		NULL		
add5	varchar(30)	YES		NULL		
img5	blob	YES		NULL		

Loading

Categories: NodeJs

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.