Node js Express Insert Data From Form into MySQL DB Tutorial

In this tutorial, you will learn store data from HTML form to MySQL database in Node JS Express app.

How to Insert Form Data in MySQL using Node js Express

Simply create the form in HTML and create a route to send the data to the app server, then connect the app server to the database and store the data through a Node JS Express project using MySQL insert into clause queries:

Step 1 – Create Node Express js App

To create a Node JS Express project directory run the command mkdir my-app && cd my-app on a CMD or terminal window:

mkdir my-app
cd my-app

Next run npm init -y to initialize a project and create a package. json file:

npm init -y

Step 2 – Create Table in MySQL Database

To create the database and table for your Node Express JS project, simply run the following SQL query for the same:

CREATE TABLE `contacts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `f_name` varchar(100) NOT NULL,
  `l_name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `message` text NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Step 3 – Install express flash ejs body-parser mysql Modules

To install some required dependencies like express flash ejs body-parser mysql dependencies: For node express js project, just use the following command on cmd or terminal window for the same:

npm install -g express-generator
npx express --view=ejs
npm install
npm install express-flash --save
npm install express-session --save
npm install body-parser --save
npm install mysql --save

Step 4 – Create HTML Markup Form

Go to views directory, and create index.ejs file inside it, and then create html form to send data on server for insertion into it to the database:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Node.js Express Save Data from Html Form to Mysql Database - Tutsmake.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container mt-4">
      <div class="card">
        <div class="card-body">
          <% if (messages.success) { %>
              <p class="alert alert-success m2-4 mb-2"><%- messages.success %></p>
          <% } %>
          <h2>Node.js Express Save Data from Html Form to Mysql Database - Tutsmake.com</h2>
          <form action="contact-us" method="POST">
            <div class="form-group">
              <label for="firstName">First Name</label>
              <input type="text" class="form-control col-lg-9" id="f_name" aria-describedby="emailHelp" placeholder="Enter first name" name="f_name">
            </div>
            <div class="form-group">
              <label for="lastName">Last Name</label>
              <input type="text" class="form-control col-lg-9" id="l_name" aria-describedby="emailHelp" placeholder="Enter last name" name="l_name">
            </div>
            <div class="form-group">
              <label for="exampleInputEmail1">Email address</label>
              <input type="email" class="form-control col-lg-9" id="exampleInputEmail1" aria-describedby="emailHelp" name="email" placeholder="Enter email">
            </div>
            <div class="form-group">
              <label for="exampleInputEmail1">Message</label>
              <textarea name="message" class="form-control col-lg-9"></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
          </form>
    </div>
  </div>
  </body>
</html>

Step 5 – Create Database Configuration File

Create database.js file and add the following code into it to connect your app to db:

var mysql = require('mysql');
var conn = mysql.createConnection({
  host: 'localhost', // Replace with your host name
  user: 'root',      // Replace with your database username
  password: '',      // Replace with your database password
  database: 'test' // // Replace with your database Name
});
conn.connect(function(err) {
  if (err) throw err;
  console.log('Database is connected successfully !');
});
module.exports = conn;

Step 6 – Create Routes in App.js

Open app.js and create routes for showing forms and storing data to MySQL database:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var db=require('./database');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))
app.use(flash());
/* GET home page. */
app.get('/', function(req, res, next) {
  res.render('contact-us', { title: 'Contact-Us' });
});
app.post('/contact-us', function(req, res, next) {
  var f_name = req.body.f_name;
  var l_name = req.body.l_name;
  var email = req.body.email;
  var message = req.body.message;
  var sql = `INSERT INTO contacts (f_name, l_name, email, message, created_at) VALUES ("${f_name}", "${l_name}", "${email}", "${message}", NOW())`;
  db.query(sql, function(err, result) {
    if (err) throw err;
    console.log('record inserted');
    req.flash('success', 'Data added successfully!');
    res.redirect('/');
  });
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
// port must be set to 3000 because incoming http requests are routed from port 80 to port 8080
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});
module.exports = app;

Step 6 – Start App Server

You can use the following command to start node js app server:

//run the below command

npm start

after run this command open your browser and hit

http://127.0.0.1:3000/

Conclusion

Store data from html form into MySQL database in node js express app; In this tutorial,you have learned how to insert data contact us from data into MySQL database using node js express app.

Recommended Node JS Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

One reply to Node js Express Insert Data From Form into MySQL DB Tutorial

  1. Hey, Thanks for making this blog it was very helpful, But what is that contact-us path that you have used in form action and some .render and .get functions. Can you Please clarify that.

Leave a Reply

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