Hey guys I’m currently coding in node.js and i’m wondering if it’s possible to grab mysql results and store them in a variable so that I can later use them.
app.get('/getemployee', (req, res) => {
let sql = 'SELECT * FROM employee WHERE id IN (' + userIp + ')'
let query = db.query (sql, (err, results) => {
if (err) {
throw err
}
console.log (results)
res.send('Emplyee details found')
})
})
I need to grab the result from the
above code and store as variable. please help if you have some knowledge.
Below
is a copy of the whole code.
const express = require ('express')
const mysql = require ('mysql')
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'nodemysql'
})
db.connect(err => {
if (err) {
throw err;
}
console.log('MySQL Connected');
});
const app = express()
app.get("/createdb", (req, res) => {
let sql = "CREATE DATABASE nodemysql";
db.query(sql, (err)=>{
if (err) {
throw err;
}
res.send("Database Created");
});
});
//create table
app.get('/createemployee', (req, res) => {
let sql = 'CREATE TABLE employee(id int AUTO_INCREMENT, name VARCHAR(255), designation VARCHAR(255), PRIMARY KEY(id))'
db.query(sql, err => {
if (err) {
throw err
}
res.send ('Employee table created')
})
})
app.get('/employee1', (req, res) => {
let post = {name:'Jake Smith', designation:'Chief Excutive Officer'}
let sql = 'INSERT INTO employee SET ?'
let query = db.query(sql, post, err => {
if (err) {
throw err
}
res.send('Employee added')
})
})
app.get('/employee2', (req, res) => {
let post = {name:'Afro Jack', designation:'Musician'}
let sql = 'INSERT INTO employee SET ?'
let query = db.query(sql, post, err => {
if (err) {
throw err
}
res.send('Employee added')
})
})
let userIp = [1,2]
app.get('/getemployee', (req, res) => {
let sql = 'SELECT * FROM employee WHERE id IN (' + userIp + ')'
let query = db.query (sql, (err, results) => {
if (err) {
throw err
}
console.log (results)
res.send('Emplyee details found')
})
})
app.listen('3000', () => {
console.log('Server started on port 3000')
});
Any help is appreciated. Thanks in advance.