Categories

Thursday, April 18, 2024
#919814419350 therichposts@gmail.com
MysqlNodejs

Node Js – Fetch Mysql Data With Nodejs

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

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 14, Angular 15, Angular 16, Angular 17, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

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