How to Insert Form Data Into the MySql Table Using Node.js?
create users.ejs
create users.ejs page in views directory of your project folder.
File Name : users.ejs
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="user-detail">
<h2>Create User Data</h2>
<form action="/users/create" method="POST">
<label>Full Name</label>
<input type="text" placeholder="Enter Full Name" name="fullName" required>
<label>Email Address</label>
<input type="email" placeholder="Enter Email Address" name="emailAddress" required>
<label>City</label>
<input type="city" placeholder="Enter Full City" name="city" required>
<label>Country</label>
<input type="text" placeholder="Enter Full Country" name="country" required>
<button type="submit">Submit</button>
</div>
</div>
</body>
</html>
Database Table
create users table in mysql database.
File Name : users
CREATE TABLE `users` (
`id` int(10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
`fullName` varchar(255) DEFAULT NULL,
`emailAddress` varchar(255) DEFAULT NULL,
`city` varchar(255) DEFAULT NULL,
`country` varchar(50) DEFAULT NULL
);
Connect Node.js Application to MySQL Database
database.js
create database.js file in your project directory.
File Name : database.js
var mysql = require('mysql');
var conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'nodeapp'
});
conn.connect(function(err) {
if (err) throw err;
console.log('Database is connected successfully !');
});
module.exports = conn;
Create Routes
create routes for inserting data –
Include database connection file database.js
Create a route /form with the GET method to display an HTML form
Create another route /create with the POST method to insert data into the MySQL database
File Name : users.js
var express = require('express');
var router = express.Router();
var db=require('../database');
router.get('/form', function(req, res, next) {
res.render('users');
});
router.post('/create', function(req, res, next) {
// store all the user input data
const userDetails=req.body;
// insert user data into users table
var sql = 'INSERT INTO users SET ?';
db.query(sql, userDetails,function (err, data) {
if (err) throw err;
console.log("User dat is inserted successfully ");
});
res.redirect('/users/form');
// redirect to user form page after inserting the data
});
module.exports = router;
Load Route Into the Root File
include user.js route file in app.js the root file
File Name : app.js
var usersRouter = require('./routes/users');
app.use('/users', usersRouter);
Run Node.js Application to Insert Data in mysql database.
File Name : app.js
Start your Node.js server using npm start the command
npm start
Open your Browser
File Name :
http://localhost:3000/users/form
File Name :
When you submit the form. The form will be redirected to the following URL to insert form data using the POST method
http://localhost:3000/users/create
Previous
Next