Receive data from multiple tables [Nodejs,MySQL] - mysql

What do I need to do to get data from multiple tables?
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '',
user : '',
password : '',
database : ''
});
connection.connect(function(){
console.log("MySQL Database is Connected");
});
app.use(express.static(__dirname + '/css'));
app.use(express.static(__dirname + '/js'));
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
app.get('/',function(req,res){
res.render('index.html');
});
app.get('/load',function(req,res){
connection.query("select * from terms WHERE status = 1",
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});
});
app.listen(7001,function(){
console.log("App is started at PORT 7001");
});
With this I can only get data from the terms table. But I need to get data from the impTerms table.
How do I get this?
Thank you

Use sql join in query , has nothing to do with node js.
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT terms.id, terms.name FROM terms JOIN impTerms ON impTerms.id= terms.id and terms.status=1";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});

There are several ways you can do,
Passing two sql queries to connection
Var sqlQuery = "select * from terms WHERE status = 1;select * from impTerms";
connection.query(sqlQuery,
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});
Output:
[
[], // array of object for terms
[] // array of object for impTerms
]
Changing select query
Var sqlQuery = "select a.*, b.* from a.terms, b.impTerms";
connection.query(sqlQuery,
function(err,rows,fields){
if(err) throw err;
res.end(JSON.stringify(rows));
});

Related

Routing to other url in node.js

I am currently working on a project where I have CRUD operation using node.js and mysql.
var mysql = require('mysql');
var express = require('express');
var session = require('express-session');
var con = mysql.createConnection({
host: "database",
user: "admin",
password: "pass",
database: "db"
});
var app = express();
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM shops where id =33", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.use('/shop', function(err) {
con.query("SELECT * FROM shops where id =34", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
app.listen('3000', () => {
console.log('Server started on port 3000');
});
I want to get the shops data using localhost:3000/shops and brands data using localhost:3000/brands. But i don't know how to do that because i am very new in node.js. Infact,Today i my first day. I someone gives me som demo project or some thing like this. I will be very thankful.
app.get('/brands',(req,res) =>{
//inside query
})
like...thiss

Express and mysql. rows are undefined

This is my code. I am writing API and I want to send information about products that client has input.
const express = require('express');
const mysql = require('mysql');
const morgan = require('morgan');
const app = express();
app.use(morgan('short'));
app.use(express.static('./public'));
// app.get('/', (req, res, next)=>{
// res.send('Hello World');
// });
function getConnection(){
return mysql.createConnection({
host: 'localhost',
user: 'root',
password:'samsung793',
database: 'demo2'
})
}
app.get('/models/:id', (req, res, next)=>{
console.log('Fetching id ' + req.params.id);
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE id=?'
const modelId = req.params.id;
connection.query( queryStr, [modelId], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> Error! Sorry for error, we are working on it!');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})
app.get('/:name', (req, res, next)=>{
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = `SELECT * FROM products WHERE MATCH(name) AGAINST(${req.params.name}, in natural language)`
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
if (err){
res.send('<h1>500 bad request</h1> <h3>Error!</h3> <h4>Sorry for error, we are working on it!</h4>');
res.sendStatus(500);
return;
//throw err;
}
console.log('Ready');
res.json(rows);
console.log(rows);
})
// res.end();
})
app.listen(3000, ()=>{
console.log('server is listening on port 3000');
} )
when I log to console the rows, it is undefined. How can I fix it? What is the problem?
Sorry for first post. I edit and add all code now. Please help me to solve this problem.
You need to check if any error occur while querying
app.get('/:name', (req, res, next) => {
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = 'SELECT * FROM products WHERE MATCH(name) AGAINST(?, in natural language mode)';
const modelName = req.params.name;
connection.query( queryStr, [modelName], (err, rows, fields)=>{
console.log('Ready');
if(err) {
console.log(err);
return res.status(500).send(err);
}
console.log(rows);
res.json(rows);
})
})
If you are using prepared statement, you do not need to pass ${req.params.name}, just pass ?
Thank you for answers. I write code here in case someone needs it.
It works this way:
app.get('/:name', (req, res, next)=>{
console.log('Fetching name ' + req.params.name);
const connection = getConnection();
const queryStr = `SELECT * FROM products WHERE MATCH(name, url) AGAINST(? IN NATURAL LANGUAGE MODE) `
const modelName = req.params.name;
connection.query( queryStr, modelName, (err, rows, fields)=>{
console.log(rows);
if (err){
res.status(404).send(" Something went wrong");
// res.sendStatus(500);
throw err;
}
console.log('Ready');
res.json(rows);
})
// res.end();
})

NodeJS Output user in browser

I made a project where i include database which i wrote on mysql and it make a json file from database and also output all users in browser but I have some problem. I want to output one user how can i do this(this is example how it must output http://localhost:8080/user/1). I used express and mysql. Please help me. Thanks.
This is my code:
'use strict';
const mysql = require('mysql');
const express = require('express');
const http = require('http');
const router = express()
// http://nodejs.org/docs/v0.6.5/api/fs.html#fs.writeFile
const fs = require('fs');
const connection = mysql.createConnection({
host: 'localhost',
user: 'lado',
password: '1234'
});
connection.connect();
connection.query('SELECT * FROM bankdb.account;', function(err, results, fields) {
if(err) throw err;
fs.writeFile('account.json', JSON.stringify(results), function (err) {
if (err) throw err;
console.log('Saved!');
});
connection.end();
});
const pool = mysql.createPool({
host: 'localhost',
user: 'lado',
password: '1234',
database: 'bankdb',
charset: 'utf8'
});
var reo ='<html><head><title>Output From MYSQL</title></head><body><h1>Output From MYSQL</h1>{${table}}</body></html>';
function setResHtml(sql, cb){
pool.getConnection((err, con)=>{
if(err) throw err;
con.query(sql, (err, res, cols)=>{
if(err) throw err;
var table =''; //to store html table
//create html table with data from res.
for(var i=0; i<res.length; i++){
table +='<tr><td>' + (i+1) +'</td><td>'+ res[i].name +'</td><td>'+ res[i].address +'</td></tr>';
}
table ='<table border="1"><tr><th>ID</th><th>Name</th><th>Amount</th></tr>'+ table +'</table>';
con.release(); //Done with mysql connection
return cb(table);
});
});
}
const sqll ='SELECT * FROM bankdb.account';
const server = http.createServer((req, res)=>{
setResHtml(sqll, resql=>{
reo = reo.replace('{${table}}', resql);
res.writeHead(200, {'Content-Type':'text/html; charset=utf-8'});
res.write(reo, 'utf-8');
res.end();
});
});
server.listen(8080, ()=>{
console.log('Server running at //localhost:8080/');
router.get('/users/:id', function(req, res, next) {
var user = users.getUserById(req.params.id);
res.json(user);
});
exports.getUserById = function(id) {
for (var i = 0; i < users.length; i++) {
if (users[i].id == id) return users[i];
}
};
});
Just get the specific user based on their id:
router.get( '/user/:id', function( req, res ) { // When visiting '/user/:id'
var id = req.params.id; // For example if you visit localhost/user/24 the id will be 24
connection.query('SELECT * FROM bankdb.account WHERE id=' + mysql.escape( id ), function(err, results, fields) {
if(err) throw err;
fs.writeFile('account.json', JSON.stringify(results), function (err) {
if (err) throw err;
console.log('Saved!');
});
connection.end();
});
} );
If you grab every user from the database, your program will use up much more memory.
Just grab the one you need and work with him.

JawsDB error connecting with Heroku

I tried to push my project to heroku and connect jawsdb with the application. I input jawsdb info into my server.js and updated it then pushed to heroku. But I'm getting this erorr and the application wont load. I think it has something to do with the way I'm setting up the database.
I am receiving the following "Access denied for user" error:
https://ibb.co/giRO5m
this is my code: server.js
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var logger = require('morgan');
var request = require('request');
var cheerio = require('cheerio');
var methodOverride = require('method-override')
var fs = require("fs");
var hbs = require('hbs');
// Set up Express
var app = express();
var router = express.Router();
//handlebars
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
// override with POST having ?_method=DELETE
app.use(methodOverride('_method'))
// Set up Mysql
var con = mysql.createConnection({
host: "t89yihg12rw77y6f.cbetxkdyhwsb.us-east-1.rds.amazonaws.com",
port: 3306,
user: "swvr0i1j9ny720mk",
password: "e3lzkqag4dmeqhup"
});
//conecting to mysql
con.connect(function(err) {
if (err) throw err;
console.log("Database connected to the matrix..");
});
con.query('CREATE DATABASE IF NOT EXISTS warehouse', function (err) {
if (err) throw err;
con.query('USE warehouse', function (err) {
if (err) throw err;
con.query('CREATE TABLE IF NOT EXISTS storage('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'link VARCHAR(255),'
+ 'item VARCHAR(255),'
+ 'stock VARCHAR(255)'
+ ')', function (err) {
if (err) throw err;
});
});
});
// Parse application/x-www-form-urlencoded
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Serve static content for the app from the "public" directory in the application directory.
app.use(express.static(__dirname + '/public'));
//prints database to page
app.get('/index', function(req,res) {
con.query('SELECT * FROM storage;', function(err, data) {
if (err) throw err;
//test it
//console.log('The solution is: ', data);
//test it
//res.send(data);
res.render('index', {storage : data});
});
});
//delete data entry
app.delete('/delete', function(req,res){
con.query('DELETE FROM storage WHERE id = ?', [req.body.id], function(err, result) {
if (err) throw err;
res.redirect('/index');
});
});
// Open Server
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
JawsDB does not let you choose the database name or create a new database name. Instead, you will need to connect via a workbench tool and see what the database name they have given you is (for example, the below show my database name JawsDB assigned).
Then, use this database in your code instead of the one you named "warehouse." For example, if I were to do this with the schema JawsDB named for me, I would use 'jdjkhrjps1cgj89h'
con.query('USE jdjkhrjps1cgj89h', function (err) {
if (err) throw err;
con.query('CREATE TABLE IF NOT EXISTS storage('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'link VARCHAR(255),'
+ 'item VARCHAR(255),'
+ 'stock VARCHAR(255)'
+ ')', function (err) {
if (err) throw err;
});
});

Change my database result to JSON

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'