Home Mysql Node Js – Fetch Mysql Data With Nodejs

Node Js – Fetch Mysql Data With Nodejs

by therichpost
0 comments
Node Js - Fetch Mysql Data With Nodejs

Hello to all, welcome to therichpost.com. In this post, I will do, Node Js – Fetch Mysql Data With Nodejs.

Working with nodejs seems everything easy. Before starting working with nodejs, I felt, It will be difficult but now it seems easy and friendly.

I am fetching mysql data with node js, with making connection with node js to mysql. I am feeling very happy to share this code because it helped me and I hope, It will help others.

Here is the working data picture:

Node Js - Fetch Mysql Data With Nodejs

 

For Install mysql package into your node js app, need to run below command into your terminal:

npm install --save mysql

Here is the working code and tested code and you need to add your js file:

/*****TheRichPost*****/
var http   = require('http');
var mysql  = require('mysql'); //Import mysql package
//Mysql Connectivity
var con    = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : 'root',
  database : 'users'

});

function getData(res){
  con.connect(function(err) {
  //Enable error
    if (err) throw err;
  //Query code began
    con.query("SELECT * FROM users", function (err, result, fields) {
      if (err) throw err;
      //console.log(result);
      res.write("<table>");
        res.write("<tr>");
        for(var column in result[0]){
            res.write("<th><label>" + column + "</label></th>");
        }
        res.write("</tr>");
        for(var row in result){
            res.write("<tr>");
            for(var column in result[ row ]){
                res.write("<td><label>" + result[ row ][ column ] + "</label></td>");       
            }
            res.write("</tr>");         
        }
        res.write("</table>");
    });
  });
}
http.createServer(function (req, res) {
 //Output on browser
 getData(res);
}).listen(8080);

 

After done above code , you just need to run below command into your terminal:

node YourFileName.js

If you have an any query related to this post, then please do comment below or ask questions.

Thank you,

Happy Coding,

Therichpost

You may also like

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.