-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.js
87 lines (72 loc) · 2.4 KB
/
script.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
79
80
81
82
83
84
85
86
const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const app = express();
const path = require('path');
const opn = require('opn');
// Create a MySQL connection
const db = mysql.createConnection({
host: 'localhost',
user: 'User',
password: 'Hinduja@123',
database: 'internship_project'
});
// Connect to the database
db.connect((err) => {
if (err) throw err;
console.log('MySQL Connected');
});
// Middleware for parsing form data
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/public', express.static('public'));
// Set up the view engine and specify the 'views' directory
app.set('views', path.join(__dirname, 'views')); // Set the absolute path to the 'views' folder
app.set('view engine', 'ejs');
// Set up your routes
app.get('/', (req, res) => {
// Retrieve data from the database
db.query('SELECT * FROM internship_project.users', (err, results) => {
if (err){
console.log(err);
}
res.render('index.ejs', { data: results });
//console.log(results);
});
});
app.post('/add', (req, res) => {
const { name, email, age, dob } = req.body;
// Validation
if (!name || !email || !age || !dob) {
res.status(400).send('All fields are required');
return;
}
// Age must be a positive integer
const ageInt = parseInt(age);
if (isNaN(ageInt) || ageInt <= 0) {
res.status(400).send('Age must be a positive integer');
return;
}
// Insert data into the MySQL database
const sql = 'INSERT INTO users (name, email, age, dob) VALUES (?, ?, ?, ?)';
const values = [name, email, age, dob];
db.query(sql, values, (err, result) => {
if (err) {
// Handle error
console.error('Error inserting data:', err);
res.send('<script>alert("Error inserting data"); window.location="/";</script>');
} else {
// Data inserted successfully
console.log('Data inserted successfully.');
// Show a success alert and redirect
res.send('<script>alert("Data inserted successfully"); window.location="/";</script>');
}
});
});
// Set up the view engine (EJS)
app.set('view engine', 'ejs');
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
opn('http://localhost:3000');
});