Querying MySQL with Node.JS and display results in webpage

10,591

Easiest way would be to use a node framework. Like express.

You will be doing something like

/*** omitting generic code for clarity ***/
app.get('/yourpage',function(req,res){

    //On request of this page initiating sql query. Assumes that the object initialization is done above.
    mySqlClient.query(
    selectQuery,
    function select(error, results, fields) {
        if(error) {
            console.log(error);
            mySqlClient.end();
            //render the template with error to be alerted
            res.render('tempaltefile',{data:null,error:error});                
        }

        if(results.length > 0) {
            //console.log(results);
            //render the template with fetched data
            res.render('tempaltefile',{data:results,error:null});
        } else {
            //console.log('No data');
            //render the template with empty data alert
            res.render('tempaltefile',{data:null,error:"no data"});
        }
        mySqlClient.end();
    });

});

reply to comments

please mention you are using this along side ph code. I think you have to biuld the node code an api and consume it in the php end.

Share:
10,591

Related videos on Youtube

D4V1D
Author by

D4V1D

PHP and Symfony back-end developer based in Paris.

Updated on October 07, 2022

Comments

  • D4V1D
    D4V1D over 1 year

    My goal is to query MySQL with Node.JS for better interactivity. My query is a simple SELECT with JOINs. I managed to construct a script that displays results in the console but I'm kind of stuck when it comes to display it in the webpage. Here is my code:

    var mysql = require('mysql');
    
    var mySqlClient = mysql.createConnection({
        host    : 'server',
        user    : 'login',
        password: 'pwd',
        database: 'db'
    });
    
    var selectQuery = 'SELECT fields FROM table t1\
                       INNER JOIN table t2\
                       ON t1.field = t2.field';
    mySqlClient.query(
        selectQuery,
        function select(error, results, fields) {
            if(error) {
                console.log(error);
                mySqlClient.end();
                return;
            }
    
            if(results.length > 0) {
                console.log(results);
            } else {
                console.log('No data');
            }
            mySqlClient.end();
        });
    

    What is the best approach to include this into the webpage? Do I need to create a httpServer with Node.JS?

    Many thanks for any help!

    EDIT I would like to use Node.JS inside a PHP application designed with Zend Framework. The Node.JS app wouldn't be the sole app of my project.

  • D4V1D
    D4V1D about 10 years
    Thanks for reply, is this compatible with an already existing front end app such as a Zend Framework app? How can I include express.js in ZF?