forked from MFikri94/crud-nodejs-mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
78 lines (70 loc) · 2 KB
/
index.js
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
//use path module
const path = require('path');
//use express module
const express = require('express');
//use hbs view engine
const hbs = require('hbs');
//use bodyParser middleware
const bodyParser = require('body-parser');
//use mysql database
const mysql = require('mysql');
const app = express();
//Create Connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'crud_db'
});
//connect to database
conn.connect((err) =>{
if(err) throw err;
console.log('Mysql Connected...');
});
//set views file
app.set('views',path.join(__dirname,'views'));
//set view engine
app.set('view engine', 'hbs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//set folder public as static folder for static file
app.use('/assets',express.static(__dirname + '/public'));
//route for homepage
app.get('/',(req, res) => {
let sql = "SELECT * FROM product";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.render('product_view',{
results: results
});
});
});
//route for insert data
app.post('/save',(req, res) => {
let data = {product_name: req.body.product_name, product_price: req.body.product_price};
let sql = "INSERT INTO product SET ?";
let query = conn.query(sql, data,(err, results) => {
if(err) throw err;
res.redirect('/');
});
});
//route for update data
app.post('/update',(req, res) => {
let sql = "UPDATE product SET product_name='"+req.body.product_name+"', product_price='"+req.body.product_price+"' WHERE product_id="+req.body.id;
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.redirect('/');
});
});
//route for delete data
app.post('/delete',(req, res) => {
let sql = "DELETE FROM product WHERE product_id="+req.body.product_id+"";
let query = conn.query(sql, (err, results) => {
if(err) throw err;
res.redirect('/');
});
});
//server listening
app.listen(8000, () => {
console.log('Server is running at port 8000');
});