Skip to content
  • About Us
  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Site Map

XpertPhp

Expertphp Is The Best Tutorial For Beginners

  • Home
  • Javascript
    • Jquery
    • React JS
    • Angularjs
    • Angular
    • Nodejs
  • Codeigniter
  • Laravel
  • Contact Us
  • About Us
  • Live Demos
Node Js Crud Operations Example Using Express With Mysql

node js crud operations example using express with mysql

Posted on December 4, 2019August 27, 2020 By XpertPhp No Comments on node js crud operations example using express with mysql

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.).

Read Also: simple hello world node js

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
1
2
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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_mac\myapp\package.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
1
npm install express -save

Below command used for form validation.

PHP
1
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
1
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
1
npm install method-override -save

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

PHP
1
npm install express-flash -save

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

PHP
1
2
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
1
npm install ejs -save

below following command using install the MySQL module

PHP
1
npm install mysql -save

The express-myconnection module used for MySQL connection.

PHP
1
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
1
2
3
4
5
6
7
8
9
10
11
12
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Node Js Crud Operations Example Using Express With Mysql - XpertPhp</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <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.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="margin-top: 50px;">

footer.ejs

1
2
3
   </div>
</body>
</html>

index.ejs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<%- include header.ejs %>    
 
<% if(errors){ %>
    <ul class="alert alert-danger">
    <% for(var i = 0; i < errors.length; i++){ %>
        <li> <%= errors[i].msg %> </li>
    <% } %>
    </ul>
<% } %>
<% if (messages.success) { %>
<div class="alert alert-success">
<strong>Success!</strong> <%- messages.success %>
</div>
<% } %>
 
<div class="row">
<div class="col-lg-10 text-center"><h2><%= title %></h2></div>
<div class="col-lg-2"><a href="/add" class="btn btn-primary">Add New Student</a></div>
</div>  
<table class="table table-bordered">
<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='/edit/<%= student.id %>' class="btn btn-info">Edit</a> &nbsp;                            
<form method="post" action="/delete/<%= student.id %>" style="float:right">
<input type="submit" name="delete" value='Delete' class="btn btn-danger" 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<%- include header.ejs %>    
<% if(errors){ %>
    <ul class="alert alert-danger">
    <% for(var i = 0; i < errors.length; i++){ %>
        <li> <%= errors[i].msg %> </li>
    <% } %>
    </ul>
<% } %>
<% if (messages.success) { %>
  <div class="alert alert-success">
      <strong>Success!</strong> <%- messages.success %>
    </div>
  <% } %>
 
<div class="row">
    <div class="col-lg-10 text-center"><h3><%= title %></h3></div>
    <div class="col-lg-2"><a href="/" class="btn btn-primary">List Student</a></div>
</div>  
 
 
<form class="form-horizontal" action="/add" method="POST">
    <div class="form-group">
      <label class="control-label col-sm-2" for="txtFname">First Name:</label>
      <div class="col-sm-10">
        <input type="text" name="txtFname" class="form-control" id="txtFname" value="<%= txtFname %>" /></td>  
      </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="txtLname">First Name:</label>
        <div class="col-sm-10">
            <input type="text" name="txtLname" class="form-control" id="txtLname" value="<%= txtLname %>" /></td>  
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="txtEmail">Email:</label>
        <div class="col-sm-10">
            <input type="email" name="txtEmail" class="form-control" id="txtEmail" value="<%= txtEmail %>" /></td>  
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="txtMobile">Mobile:</label>
        <div class="col-sm-10">
            <input type="text" name="txtMobile" class="form-control" id="txtMobile" value="<%= txtMobile %>" /></td>  
        </div>
    </div>
    <div class="form-group">        
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-primary">Add</button>
      </div>
    </div>
  </form>
<%- include footer.ejs %>

edit.ejs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<%- include header.ejs %>    
        
<% if(errors){ %>
    <ul class="alert alert-danger">
    <% for(var i = 0; i < errors.length; i++){ %>
        <li> <%= errors[i].msg %> </li>
    <% } %>
    </ul>
<% } %>
 
<% if (messages.success) { %>
<div class="alert alert-success">
    <strong>Success!</strong> <%- messages.success %>
  </div>
<% } %>
 
<div class="row">
    <div class="col-lg-10 text-center"><h3><%= title %></h3></div>
    <div class="col-lg-2"><a href="/" class="btn btn-primary">List Student</a></div>
</div>  
 
<form class="form-horizontal" action="/edit/<%= id %>" method="POST">
    <input type="hidden" name="_method" value="PUT" />
    <div class="form-group">
      <label class="control-label col-sm-2" for="txtFname">First Name:</label>
      <div class="col-sm-10">
        <input type="text" name="txtFname" class="form-control" id="txtFname" value="<%= txtFname %>" /></td>  
      </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="txtLname">First Name:</label>
        <div class="col-sm-10">
            <input type="text" name="txtLname" class="form-control" id="txtLname" value="<%= txtLname %>" /></td>  
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="txtEmail">Email:</label>
        <div class="col-sm-10">
            <input type="email" name="txtEmail" class="form-control" id="txtEmail" value="<%= txtEmail %>" /></td>  
        </div>
    </div>
    <div class="form-group">
        <label class="control-label col-sm-2" for="txtMobile">Mobile:</label>
        <div class="col-sm-10">
            <input type="text" name="txtMobile" class="form-control" id="txtMobile" value="<%= txtMobile %>" /></td>  
        </div>
    </div>
    <div class="form-group">        
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-primary">Update</button>
      </div>
    </div>
  </form>
<%- include footer.ejs %>

Please follow and like us:
error
fb-share-icon
Tweet
fb-share-icon

Recommended Posts:

  • Codeigniter Single and Multiple records Insert Query
  • Laravel 6 Socialite Twitter Login Tutorial Example
  • Laravel 7 GEO Chart Example using lavacharts
  • Laravel 6 Ajax Image Upload example tutorial
  • laravel eloquent WhereDate query example
MySql, Nodejs Tags:crud operation, nodejs, nodejs from scratch, nodejs with express, nodejs with mysql

Post navigation

Previous Post: node js routes in separate file using express
Next Post: File/Image Upload With Multer in Node js and Express

Categories

  • Ajax
  • Angular
  • Angularjs
  • Bootstrap
  • Codeigniter
  • Css
  • Htaccess
  • Javascript
  • Jquery
  • Laravel
  • MongoDB
  • MySql
  • Nodejs
  • Php
  • React JS
  • Shopify Api
  • Ubuntu

Tags

angular 10 tutorial angular 11 ci tutorial codeigniter 4 image upload Codeigniter 4 Tutorial codeigniter tutorial CodeIgniter tutorial for beginners codeigniter with mysql crud operation eloquent relationships file upload File Validation form validation Image Upload jQuery Ajax Form Handling jquery tricks jquery tutorial laravel 6 Laravel 6 Eloquent Laravel 6 Model laravel 6 relationship laravel 6 relationship eloquent Laravel 6 Routing laravel 7 Laravel 7 Eloquent laravel 7 routing laravel 7 tutorial Laravel 8 laravel 8 example laravel 8 tutorial laravel 9 example laravel 9 tutorial Laravel Framework laravel from scratch Laravel Socialite laravel social login nodejs pagination payment gateway php with mysql react js tutorial rewrite rule send mail validation wysiwyg editor

Latest Posts

  • How to Convert Date and Time from one timezone to another in php
  • how to get current date and time in php
  • Drag and Drop Reorder Items with jQuery, PHP & MySQL
  • Laravel 9 Toastr Notifications Example Tutorial
  • Laravel 9 CRUD Operation Example Using Google Firebase
  • Laravel 9 CKeditor Image Upload With Example
  • Laravel 9 Summernote Image Upload With Example
  • Laravel 9 Stripe Payment Gateway Integrate Example
  • How To Send Email Using Mailtrap In Laravel 9
  • Laravel 9 Fullcalendar Ajax Example Tutorial

Tools

  • Compound Interest Calculator
  • Hex to RGB Color Converter
  • Pinterest Video Downloader
  • Age Calculator Online
  • Convert JSON to PHP Array Online
  • JavaScript Minifier
  • CSS Beautifier
  • CSS Minifier
  • JSON Beautifier
  • JSON Minifier

Copyright © 2018 - 2022,

All Rights Reserved Powered by XpertPhp.com