简体   繁体   English

使用 Node.JS 查询 MySQL 并在网页中显示结果

[英]Querying MySQL with Node.JS and display results in webpage

My goal is to query MySQL with Node.JS for better interactivity.我的目标是使用 Node.JS 查询 MySQL 以获得更好的交互性。 My query is a simple SELECT with JOIN s.我的查询是一个带有JOIN的简单SELECT 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?我需要用 Node.JS 创建一个 httpServer 吗?

Many thanks for any help!非常感谢您的帮助!

EDIT I would like to use Node.JS inside a PHP application designed with Zend Framework.编辑我想在使用 Zend Framework 设计的 PHP 应用程序中使用 Node.JS。 The Node.JS app wouldn't be the sole app of my project. Node.JS 应用程序不会是我项目的唯一应用程序。

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.请提及您在 ph 代码旁边使用它。 I think you have to biuld the node code an api and consume it in the php end.我认为您必须将节点代码构建为 api 并在 php 端使用它。

I was in the same situation as you, I could not connect to MySQL Zend since NodeJS.我和你的情况一样,自从 NodeJS 以来我无法连接到 MySQL Zend。 My solution was to use:我的解决方案是使用:

Finally, restart the computer to apply the new install.最后,重新启动计算机以应用新安装。

  • In your server.js file, you can use this code to connect to your HostDB:在您的 server.js 文件中,您可以使用以下代码连接到您的 HostDB:

    var app = require('http').createServer(handler), mysql = require('mysql'), connectionsArray = [], connection = mysql.createConnection({ host: 'localhost', user: 'USERNAME MYSQL', password: 'PASSWORD MYSQL', database: 'NAME MYSQLDATABASE', port: 3306 }); var app = require('http').createServer(handler), mysql = require('mysql'), connectionsArray = [], connection = mysql.createConnection({ host: 'localhost', user: 'USERNAME MYSQL', password : 'PASSWORD MYSQL', 数据库: 'NAME MYSQLDATABASE', 端口: 3306 });

app.post('/qr', function(req, res) {
  console.log("Check QR code.");
  let now = moment().format('MMMM Do YYYY, h:mm:ss a');
  let subnow = now.substr(0, 8);
  let subnowwild = subnow + "%";
  connection.query("select exists (select * from visit where timeIn like ?)", subnowwild, function(err, result) {
  if (err) throw err;
  console.log(result);
    if(result = 0) {
     res.redirect(307, '/savedata');
    }
    else {
     res.redirect(307, '/updatedata');
    }
  });
});

So I wanted to see what a response was like when getting data with mysql and this webpage showed up but did not show the answer I was looking for.所以我想看看用 mysql 获取数据时的响应是什么样的,这个网页出现了,但没有显示我正在寻找的答案。

You can also use res.send(result);你也可以使用res.send(result); if you want the query to return the data as a json response.如果您希望查询将数据作为 json 响应返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM