Change my database result to JSON - mysql

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'

Related

I want my query result to be displayed in format of actual table Node.js HTML CSS

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

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

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.

nodejs mysql using data in other modules/files

I'm trying to get data from my DB and use it in different modules of my app. My app is split in a lot of modules which I require where I need them.
My connectDB.js module looks like this
var mysql = require('mysql');
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "pw",
database : "something"
});
db.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Database connected');
});
function select(query)
{
db.query(query,function(err,rows){
if(err) throw err;
return rows;
});
}
module.exports =
{
select
}
I was hoping to simply just require this module and then do a something like
db.select('SELECT * FROM users');
But for some reason the return value is always "undefined"
Sending queries inside the connectDB module works as expected returning the correct data. But I can't use my function to get data.
Is there something wrong here with my logic? Can you help what I am doing wrong?
As I remember, connection.query will return result async, so you need to wrap it with callback or Promise.
var mysql = require('mysql');
function DB {
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "pw",
database : "something"
});
db.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Database connected');
});
this.select = function(query, callback) {
db.query(query,function(err,rows){
if(err) throw err;
callback(rows);
});
}
//Promise version
this.selectPromise = function(query) {
return new Promise(function(resolve, reject){
db.query(query,function(err,rows){
if(err) reject(err);
resolve(rows);
});
});
}
}
module.exports = DB;
How to use:
var DB = require('your-module');
var db = new DB();
db.query('select * from table', function(result) {
console.log(result);
});
db.selectPromise('select * from table').then(function(result) {
console.log(result);
});
Make the following change to your code
module.exports =
{
select: select
}
And you forgot about callback function
function select(query, callback)
{
db.query(query,function(err,rows){
if(err) throw err;
return callback(rows);
});
}
Then you can pass a function like this:
db.select('SELECT * FROM users', function(rows) {
// Do stuff with rows
});

Retrieving JSON response from local database

I am trying to print JSON response in my local browser of the data from my local system
I have my code::
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var mysql=require('mysql');
var async=require('async');
var app=express();
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'ImagePostingDB'
});
connection.connect();
app.set('port',process.env.PORT||7002);
app.use('/Details',express.static(__dirname+'/public/images'));
app.use(express.bodyParser());
app.get('/DescriptionSortedPrice/',function(request,response){
var name_of_restaurants;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants
});
});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
When i tried with postman:: i have no JSON response::
How to resolve this ?
or
how to find my root cause of the problem
{Edit}
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var mysql=require('mysql');
var async=require('async');
var app=express();
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'ImagePostingDB'
});
connection.connect(function(err) { if ( !err ) { console.log("Connected to MySQL"); } else if ( err ) { console.log(err); } });
app.set('port',process.env.PORT||7002);
app.use('/Details',express.static(__dirname+'/public/images'));
app.use(express.bodyParser());
app.get('/DescriptionSortedPrice/',function(request,response){
connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields) {
if (err) {
return response.send(500, err.message);
}
response.json({
'restaurants' : rows
});
});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
I have a Snapshot in my command prompt like this::
First: can you confirm that the server doesn't crash when you launch the request? A response code of 0 usually means that the connection was cut (or that no response was sent at all).
async.series is supposed to be used to call multiple asynchronous functions in series: there's no need to use it if you only call one function.
The callbacks in async.series follow Node.js's callback style, which means they take an error (or null) as a first parameter, and then the results of the function. But you don't send it any arguments: callback(). However, your code still works because you use a local variable name_of_restaurants that you overwrite in your asynchronous function. Be careful because that's not how you are supposed to use this pattern. Here is a more elegant solution:
app.get('/DescriptionSortedPrice/',function(request,response){
connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields) {
if (err) {
console.log('Encountered an error:', err.message);
return response.send(500, err.message);
}
console.log('Found results:', rows);
response.json({
'restaurants' : rows
});
});
});