I am using express to insert/list some records from a mysql db. Everything works fine (insert/select) but how do I render the list function after insert was completed? Do I have to re-invoke the select statement?
var mysql = require('mysql');
exports.create = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('INSERT INTO wall (message) VALUES ("' + req.body.message + '")', function(err, result) {
if (err)
throw err
// is this correct? <===
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
// end
connection.end();
});
};
exports.list = function(req, res) {
var connection = mysql.createConnection({user: 'root', password: 'password', database: 'test'});
connection.query('SELECT * FROM wall', function(err, rows) {
if (err)
throw err
if (rows)
res.render('wall', {title: 'Wall', data: rows});
});
connection.end();
};
Yes, you do have to SELECT again, and your code is generally correct. I would refactor the common part between list and the part you're asking about, I would not list users and passwords in source files, and make other minor modifications, but generally it's correct.
I read the docs more carefully and i found
res.redirect();
so for my example, it works just fine to do
res.redirect('/wall');
to make a GET request to /wall route. The data will come as this route fetching the list of messages. Thats ok for me.
Related
I am building a project for Database Course.
I am already done with Front End. I built the front end using Tailwind CSS.
Now I've started working on the backend and getting data from the database and display on my website using Node.js
I am a beginner and I want the result of the query to be styled and formatted like an actual table.
So I need help as I didn't find a reliable solution on the internet
I AM ATTACHING THE OUTPUT RESULT AND THE KIND OF RESULT I WANT.
Here is my Node.js code
var mysql = require('mysql');
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "12345678",
database: "mydb"
});
var sqlQuery = "SELECT username FROM Users";
con.connect(function (err) {
if (err) throw err;
console.log("Connected!");
// con.query(sqlQuery, function (err, result) {
// if (err) throw err;
// console.log(result);
// });
});
// display query result on host
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
// display query result on host
con.query(sqlQuery, function (err, result) {
if (err) throw err;
//show result in table format
res.end(JSON.stringify(result));
});
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
CURRENT OUTPUT
OUTPUT I WANT
I have this code where I am trying to receive data from the user and it should be inserted into the db directly without any module just a controller, can someone tell me how can I do that, I know we can get the user data in the req.body, but I don't know how to send it back to the controller here is the
P.S user will be sending around 10 or more fields that will be inserted
here is the code
controller
sql.query(`INSERT INTO Admin (LoginID,Password,Preference,Name,Last Name) values ? ` , (err, result)=> {
if (err) {
console.error('Something bad happened: ' + err);
return res.status(500);
}
console.log('Response from controller', result);
res.json(result);
});
}
module.exports = {test}
and this is the router page
Router
router.post('/CreateOrganizer',(req,res)=>{
organizer.test
})
This is how you should proceed:
const con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
app.post('',(req, res, next) => {
const user = req.body;
// use the same key in the query that you are getting from body.
const sql = "INSERT INTO Admin (LoginID,Password,Preference,Name,Last Name)
VALUES ('user.LoginID', 'user.Password', 'user.Preference', 'user.Name''user.LastName')";
con.query(sql, function (err, result) {
if (err) {
console.error('Something bad happened: ' + err);
return res.status(500);
}
console.log("1 record inserted");
});
})
There are several tutorials available online that can help you to achieve the same.
I want to display all the values from two tables from my database and display it as console.log. If I write a single query in var sql and display it as console.log(results) it works but not for multiple queries.
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors?; SELECT * FROM member_info?;'
connection.query(sql, function(err, results, fields){
if (!err) {
// res.send(JSON.stringify(results[0]));
// res.send(JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
I was able to get it to work but I had to do 2 things:
First I renamed the tables to remove the question mark as it was always getting translated to a '1' and the table name no longer matched what was in the DB.
Second, I added an array to the connection.query(). After that it worked just fine.
More info here
var express = require('express');
var app = express();
let mysql = require('mysql')
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'pitch_perfect_db2',
multipleStatements: true
})
app.get('/',(req, res) => {
connection.connect();
var sql = 'SELECT * FROM investors; SELECT * FROM member_info;';
//var sql = 'SELECT * FROM investors;';
connection.query(sql, [1, 2], function(err, results, fields){
if (!err) {
res.send(JSON.stringify(results[0]) + JSON.stringify(results[1]));
console.log('hey');
//console.log(results);
console.log(results[0]);
console.log(results[1]);
} else{
console.log('Error while performing query.');
console.log(err);
}
});
connection.end();
})
//app.listen(port, () => console.log('Server Started pn port ${port}'));
app.listen(3002);
In node you don't use ; in your sql statements. Assuming both the investors and member_info tables have the same number of columns, you will need to use this:
var sql = 'SELECT * FROM investors UNION ALL SELECT * FROM member_info';
Alternatively, if investors and member_info are unrelated tables, you will need to journey into callback hell to get what you need:
app.get('/',(req, res) => {
connection.connect();
var sql1 = 'SELECT * FROM investors';
var sql2 = 'SELECT * FROM member_info?';
connection.query(sql1, function(err, investors){
if (err) throw err; //you should use this for error handling when in a development environment
console.log(investors); //this should print
connection.query(sql2, function(err, members) {
if (err) throw err;
console.log(members);
res.render('your view', {investors:investors, members:members});
});
});
});
If you decide on the latter approach, I would urge you to reconsider your database layout.
If either of the tables in your examples have a foreign key relation with each other, you should definitely be using some kind of JOIN statement on these tables, instead of a UNION.
I just started learning node.js...
Here is an example of my code. In this example everything works.
But, I have a question. How to make several SQL queries and send results to template?
At the moment I can only do this for one query...
Thanks.
//connection database
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'test'
});
connection.connect(function (err){
if (err) throw err;
console.log('Database connected . . . \n\n');
});
router.get('/', function(req, res, next) {
var sql = 'SELECT * FROM `test`';
connection.query(sql, function(err, rows, field){
if (err) throw err;
res.render('index', {
data: rows
})
});
});
Here is an answer following my comment since you mentioned you couldn't figure it out on your own.
First snippet uses promises, a quick helper function, but no external library. Second snippet uses the external async.js library and is a bit more callback-heavy. Both of them tackle the problem assuming we want the queries to be executed in parallel.
With promises
router.get('/', async function(req, res, next) {
var queries = ['SELECT * FROM `test`',
'SELECT * FROM `test2`',
'SELECT * FROM `test3`'];
var allResults = [];
/*transform our `query` array into an array of promises, then
await the parallel resolution of all the promises*/
var allQueryRows = await Promise.all(queries.map(query => promiseQuery(query)));
/*'allQueryRows' is an array of rows, so we push each of those
into our results*/
allQueryRows.forEach(function(rows){
allResults.push(...rows);
});
res.render('index', {
data: allResults
})
});
function promiseQuery(sqlQuery){
return new Promise((resolve, reject) => {
connection.query(sqlQuery, function(err, rows, field){
if(err)
return reject(err);
resolve(rows);
})
})
}
With callbacks and async.js
const async = require('async');
router.get('/', function(req, res, next) {
var queries = ['SELECT * FROM `test`',
'SELECT * FROM `test2`',
'SELECT * FROM `test3`'];
var allResults = [];
async.each(queries, function(sqlQuery, callback){
connection.query(sqlQuery, function(err, rows, field){
if(err)
throw err;
allResults.push(...rows);
callback();
});
}, function(){
res.render('index', {
data: allResults
});
});
});
I would like to know how to get the result of my query to be a JSON response in Node.js. Currently, I am getting a result from my DB that is in JSON but I cannot access the values in it. My code is below.
connection.connect();
connection.query('select * from ttnews order by post_date DESC Limit 0,10',
function (error, results, fields) {
if (error) throw error;
console.log(results);
});
connection.end();
responseJSON.response = results[0].headline;
callback(null, responseJSON);
By the line responseJSON.response = results[0].headline I am getting an error results is undefined
Any help will be appreciated.
Try this code
var express = require('express');
var app = express();
var mysql = require('mysql');
var readline = require('readline');
var con = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'cmd'//your database name
});
con.connect(function(err){
if(err){
console.log('Error Connecting to Database');
}
});
app.get('/', function(req, res){
con.query('SELECT * FROM ttnews order by post_date DESC Limit 0,10',function(error, data){
if(error) {
console.log(error)
}else{
res.json(data)
}
});
});
app.listen(3000,function(){
console.log('server listening on 3000');
});
Hope this helps...
With Express 4.x, the output rows from mysql db is in json format.
For example,
sqlConnect.connection.query('SELECT * from users', function(err, rows, fields){
if (err) {
console.log("Querying error");
} else {
console.log(rows);
}
sqlConnect.connection.end();
});
The output is of the form
[ RowDataPacket {
id: 1,
username: 'Dani',
password: '1q2w3e4r',
verified: 0 } ]
So now you can get the individual values using the . operator. For example, console.log(rows[0].username) will log the value 'Dani'