node js crud operations example using express with mysql – onlinecode

node js crud operations example using express with mysql – onlinecode

In this post we will give you information about node js crud operations example using express with mysql – onlinecode. Hear we will give you detail about node js crud operations example using express with mysql – onlinecodeAnd how to use it also give you demo for it if it is necessary.

In this article, we will show how to create node js crud operations example using express with MySQL. here we will create a simple application using express. so we can easily manage the HTTP request (such as GET, POST, PUT, DELETE, etc.).

so you can follow the below steps for create node js crud operation example using express with MySQL.

Overview

Step 1: Create the Application Directory.

Step 2: Create an application using npm init

Step 3: Install helpful Packages

Step 4: Create database and table using express-myconnection

Step 5: Setting Database Configuration

Step 6: Create an app.js file

Step 7: Create student.js file

Step 8: Create a view file using ejs

Node js CRUD Example With MySql

Step 1: Create an Application Directory

First, we will open the command prompt and create the application directory in our directory. for this, you can follow the below command.

PHP
mkdir node_crud_mysql_ejs
cd node_crud_mysql_ejs

Step 2: Create an application using npm init

The “npm init” command through we can create a new package.json file in our application directory. when we build a new app at that time we use this command. Node.js will need to have a package.json file because includes the application related packages and application data.

Here below command helps to initialization our application.

PHP
npm init

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See 'npm help json' for definitive documentation on these fields
and exactly what they do.

Use 'npm install ' afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (myapp) node_crud_mysql_ejs
version: (1.0.0)
description: node_crud_mysql_ejs
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to E:test_macmyapppackage.json:

{
  "name": "node_crud_mysql_ejs",
  "version": "1.0.0",
  "description": "node_crud_mysql_ejs",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Is this OK? (yes) yes

Step 3: Install helpful Packages

Expess.js is a free and open-source framework and it’s a web application framework for Node.js. we can manage routes, create restful API, handle the request and response, and also create MVC structure using the express.js. Npm stands for the node package manager. npm, help to install node packages and manage the types of dependencies.Here below command help to install express package.

PHP
npm install express -save

Below command used for form validation.

PHP
npm install express-validator -save

This body-parser module parses JSON request and that allows you to access req.body from within your routes.

PHP
npm install body-parser -save

When we are submitting the form that time does not support some request like as PUT and DELETE. so we can easily pass data using this module.

PHP
npm install method-override -save

The express-flash module used for the show message after inserted record or deleted record.

PHP
npm install express-flash -save

The cookie-parser and install express-session module used for temporary store data.

PHP
npm install cookie-parser -save
npm install express-session -save

EJS standard for an Embedded Javascript Templating and it is a simple templating language.

PHP
npm install ejs -save

below following command using install the MySQL module

PHP
npm install mysql -save

The express-myconnection module used for MySQL connection.

PHP
npm install express-myconnection -save

Step 4: Create database and table using express-myconnection

we can use the below command to create a database, otherwise, we can directly create a database on PHPMyAdmin.

PHP
create database node_crud_mysql_ejs;
use node_crud_mysql_ejs;
 
CREATE TABLE students (
id int(11) NOT NULL auto_increment,
first_name varchar(100) NOT NULL,
last_name varchar(100) NOT NULL,
email varchar(100) NOT NULL,
mobile varchar(100) NOT NULL,
created_at datetime NOT NULL,
PRIMARY KEY (id)
);

Step 5: Setting Database Configuration

After complete the installation of packages. we will database configuration. now we will create config.js in the application directory and paste the below code in this file.

PHP
var config = {
    database: {
        host:     'localhost',
        user:     'root',
        password: '',      
        port:     3306,
		db:       'node_crud_mysql_ejs'
	},
    server: {
        host: '127.0.0.1',
        port: '3000'
    }
};
 
module.exports = config;

Step 6: Create an app.js file

Now, we will take a new file and paste follow below code in this file and save as app.js.

PHP
var express = require('express');
var app = express();
var mysql = require('mysql');
var myConnection  = require('express-myconnection');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var methodOverride = require('method-override');
var expressValidator = require('express-validator');
var config = require('./config');
var students = require('./controllers/student');
 
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser('keyboard cat'));
app.use(session({ 
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}));
app.use(flash());

var dbOptions = {
    host:     config.database.host,
    user:     config.database.user,
    password: config.database.password,
    port:     config.database.port, 
    database: config.database.db
};

app.use(myConnection(mysql, dbOptions, 'pool'));
app.set('view engine', 'ejs');
app.use(methodOverride(function (req, res) {
  if (req.body && typeof req.body === 'object' && '_method' in req.body) {
    // look in urlencoded POST bodies and delete it
    var method = req.body._method
    delete req.body._method
    return method
  }
}));

app.use('/', students);
 
app.listen(3000, function(){
    console.log('Server running at port 3000: http://localhost:3000');
});

Step 7: Create student.js file

Now, we will take a new file and paste follow below code in this file and save as student.js in the controller’s directory.

PHP
var express = require('express');
var router  = express();
var dateTime = require('node-datetime');
var dt = dateTime.create();
var curdate = dt.format('Y-m-d H:M:S');
const { check, validationResult } = require('express-validator');


//following route to the get of student list
router.get('/', function(req, res, next) {
    req.getConnection(function(error, conn) {
        conn.query('SELECT * FROM students ORDER BY id DESC',function(err, rows, fields) {
            if (err) {
                res.render('index', {
                    title: 'Student List', 
                })
            } else {
                res.render('index', {
                    title: 'Student List', 
                    data: rows,
                    errors :''
                });
            }
        });
    });
});
 
//following route to the show add student form
router.get('/add', function(req, res, next){    
    res.render('add', {
        title: 'Add New Student',
        errors :'',
        txtFname: '',
        txtLname: '',
        txtEmail: '',        
        txtMobile: ''        
    })
});

//following route to the add student data
router.post('/add', [
    check('txtFname').not().isEmpty().withMessage('First Name is Required Field'),
    check('txtLname').not().isEmpty().withMessage('Last Name is Required Field'),
    check('txtEmail').isEmail().normalizeEmail().withMessage('Email is Not Valid'),
    check('txtMobile').not().isEmpty().withMessage('Mobile is Required Field')
  ],
  function (req, res) {
    const errors = validationResult(req);

    if(!errors.isEmpty()){
        res.render('add',{
            errors :errors.array(),
            title: 'Add New User',
            errors :'',
            txtFname: req.body.txtFname,
            txtLname: req.body.txtLname,
            txtEmail: req.body.txtEmail,   
            txtMobile: req.body.txtMobile
        });
       
    }else{

        var student = {
            first_name: req.body.txtFname.trim(),
            last_name: req.body.txtLname.trim(),
            email: req.body.txtEmail.trim(),
            mobile: req.body.txtMobile.trim(),
            created_at: curdate
        }
        
        req.getConnection(function(error, conn) {
            conn.query('INSERT INTO students SET ?', student, function(err, result) {
                           
                req.flash('success', 'Data added successfully!')
                res.render('add', {
                    title: 'Add New Student',
                    errors :'',
                    txtFname: '',
                    txtLname: '',
                    txtEmail: '',        
                    txtMobile: ''                      
                });
                
            });
        });
    }
  });

//following route to the show edit form student data
router.get('/edit/(:id)', function(req, res, next){
    req.getConnection(function(error, conn) {
        conn.query('SELECT * FROM students WHERE id = ' + req.params.id, function(err, rows, fields) {
       
            if (rows.length <= 0) {
                req.flash('error', 'Student not found with id = ' + req.params.id);
                res.redirect('/');
            }
            else { 
                
                res.render('edit', {
                    title: 'Edit Student', 
                    errors :'',
                    id: rows[0].id,
                    txtFname: rows[0].first_name,
                    txtLname: rows[0].last_name,
                    txtEmail: rows[0].email,                    
                    txtMobile: rows[0].mobile,
                    created_at: curdate                    
                });
            }            
        });
    });
});

//following route to the edit student data
router.put('/edit/(:id)', [
    check('txtFname').not().isEmpty().withMessage('First Name is Required Field'),
    check('txtLname').not().isEmpty().withMessage('Last Name is Required Field'),
    check('txtEmail').isEmail().normalizeEmail().withMessage('Email is Not Valid'),
    check('txtMobile').not().isEmpty().withMessage('Mobile is Required Field')
  ],
  function (req, res) {
    const errors = validationResult(req);

    if(!errors.isEmpty()){
        res.render('edit',{
            errors :errors.array(),
            title: 'Edit User',
            id: req.params.id,
            txtFname: req.body.txtFname,
            txtLname: req.body.txtLname,
            txtEmail: req.body.txtEmail,   
            txtMobile: req.body.txtMobile
        });
       
    }else{

        var student = {
            first_name: req.body.txtFname.trim(),
            last_name: req.body.txtLname.trim(),
            email: req.body.txtEmail.trim(),
            mobile: req.body.txtMobile.trim()
        }
        
        req.getConnection(function(error, conn) {
            conn.query('UPDATE students SET ? WHERE id = ' + req.params.id, student, function(err, result) {
                           
                req.flash('success', 'Data updated successfully!')
                res.render('edit', {
                    title: 'Edit Student',
                    errors :'',
                    id: req.params.id,
                    txtFname: req.body.txtFname,
                    txtLname: req.body.txtLname,
                    txtEmail: req.body.txtEmail,   
                    txtMobile: req.body.txtMobile                   
                });
                
            });
        });
    }
  });

 
//Below following route to the delete student data
router.delete('/delete/(:id)', function(req, res, next) {
    var student = { id: req.params.id };
    
    req.getConnection(function(error, conn) {
        conn.query('DELETE FROM students WHERE id = ' + req.params.id, student, function(err, result) {
            if (err) {
                res.redirect('/');
            } else {
                req.flash('success', 'Student deleted successfully! id = ' + req.params.id);
                res.redirect('/');
            }
        });
    });
});
 
module.exports = router;

Step 8: Create a view file using js

Finally, we will create header.ejs, footer.ejs, index.ejs, add.ejs and edit.ejs files in view directory.

header.ejs

PHP
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Node Js Crud Operations Example Using Express With Mysql - onlinecode</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="#">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0https://onlinecode.org/js/bootstrap.min.js"></script>
</head>
<body>
<div  style="margin-top: 50px;">

footer.ejs

   </div> 
</body>
</html>

index.ejs

<%- include header.ejs %>    

<% if(errors){ %>
    <ul >
    <% for(var i = 0; i < errors.length; i++){ %>
        <li> <%= errors[i].msg %> </li>
    <% } %>
    </ul>
 <% } %>
 
<% if (messages.success) { %>
<div >
	<strong>Success!</strong> <%- messages.success %>
	</div>
<% } %>

<div >
	<div ><h2><%= title %></h2></div>
	<div ><a href="http://tridentsportscars.com/?big=add" >Add New Student</a></div>
</div>   
 
<table >
 
	<thead>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Mobile</th>
        <th>Action</th>
      </tr>
    </thead>
	<tbody>

		<% if (data) { %>
		<% data.forEach(function(student){ %>
			<tr>
				<td><%= student.first_name %></td>
				<td><%= student.last_name %></td>
				<td><%= student.email %></td>
				<td><%= student.mobile %></td>
				<td>
					<div style="float:left">
						<a href="http://tridentsportscars.com/?big=edit/<%= student.id %>" >Edit</a> &nbsp;                            
						<form method="post" action="/delete/<%= student.id %>" style="float:right">
							<input type="submit" name="delete" value='Delete'  onClick="return confirm('Are you sure you want to delete?')" />
							<input type="hidden" name="_method" value="DELETE" />
						</form>
					</div>
				</td>
			</tr>
		<% }) %>
		<% } %>
    </tbody>
</table>
<%- include footer.ejs %>

add.ejs

<%- include header.ejs %>    
 
<% if(errors){ %>
    <ul >
    <% for(var i = 0; i < errors.length; i++){ %>
        <li> <%= errors[i].msg %> </li>
    <% } %>
    </ul>
 <% } %>
 
 <% if (messages.success) { %>
  <div >
      <strong>Success!</strong> <%- messages.success %>
    </div>
  <% } %>

<div >
    <div ><h3><%= title %></h3></div>
    <div ><a href="http://tridentsportscars.com/?big=" >List Student</a></div>
</div>   


<form  action="/add" method="POST">
    <div >
      <label  for="txtFname">First Name:</label>
      <div >
        <input type="text" name="txtFname"  id="txtFname" value="<%= txtFname %>" /></td>  
      </div>
    </div>
    <div >
        <label  for="txtLname">First Name:</label>
        <div >
            <input type="text" name="txtLname"  id="txtLname" value="<%= txtLname %>" /></td>  
        </div>
    </div>
    <div >
        <label  for="txtEmail">Email:</label>
        <div >
            <input type="email" name="txtEmail"  id="txtEmail" value="<%= txtEmail %>" /></td>  
        </div>
    </div>
    <div >
        <label  for="txtMobile">Mobile:</label>
        <div >
            <input type="text" name="txtMobile"  id="txtMobile" value="<%= txtMobile %>" /></td>  
        </div>
    </div>
    <div >        
      <div >
        <button type="submit" >Add</button>
      </div>
    </div>
  </form>
 
<%- include footer.ejs %>

edit.ejs

<%- include header.ejs %>    
        
<% if(errors){ %>
    <ul >
    <% for(var i = 0; i < errors.length; i++){ %>
        <li> <%= errors[i].msg %> </li>
    <% } %>
    </ul>
 <% } %>

<% if (messages.success) { %>
<div >
    <strong>Success!</strong> <%- messages.success %>
  </div>
<% } %>
 

<div >
    <div ><h3><%= title %></h3></div>
    <div ><a href="http://tridentsportscars.com/?big=" >List Student</a></div>
</div>   

<form  action="/edit/<%= id %>" method="POST">
    <input type="hidden" name="_method" value="PUT" />
    <div >
      <label  for="txtFname">First Name:</label>
      <div >
        <input type="text" name="txtFname"  id="txtFname" value="<%= txtFname %>" /></td>  
      </div>
    </div>
    <div >
        <label  for="txtLname">First Name:</label>
        <div >
            <input type="text" name="txtLname"  id="txtLname" value="<%= txtLname %>" /></td>  
        </div>
    </div>
    <div >
        <label  for="txtEmail">Email:</label>
        <div >
            <input type="email" name="txtEmail"  id="txtEmail" value="<%= txtEmail %>" /></td>  
        </div>
    </div>
    <div >
        <label  for="txtMobile">Mobile:</label>
        <div >
            <input type="text" name="txtMobile"  id="txtMobile" value="<%= txtMobile %>" /></td>  
        </div>
    </div>
    <div >        
      <div >
        <button type="submit" >Update</button>
      </div>
    </div>
  </form>
<%- include footer.ejs %>

Please follow and like us:

Hope this code and post will helped you for implement node js crud operations example using express with mysql – onlinecode. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

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

29  +    =  30

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US