mysql 如何使用Nodejs在html上显示SQL中的不同表

unhi4e5o  于 12个月前  发布在  Mysql
关注(0)|答案(2)|浏览(135)

我有一个expressjs应用程序,我想从不同的或多个表中的数据库计数记录,并在HTML上显示结果在单独的div。代码工作没有错误,但问题是,我得到相同的结果从一个表计数到我的HTML页面上的所有div

var express = require('express');
var mysql = require('mysql');
var bodyParser  = require("body-parser");
var app = express();

app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + "/public"));

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'test',
    password : 'test',
    database : 'test'
});

app.get("/", function(req, res){
    // Find count of users in DB
    var q = "SELECT COUNT(*) AS count FROM section1"; //count first table
    var q2 = "SELECT COUNT(*) AS count2 FROM section2"; //count second table
    connection.query(q, q2, function(err, results){
        if(err) throw err;

        var count = results[0].count; //i want to count table1
        var count2 = results[0].count; // i want to count table2

        //send values to html in different divs as count and count2
        res.render('home', { count: count, count2: count })   
    });  
});
app.listen(3000, function(){
    console.log("Server running on 3000!");
});

字符串
和我的html代码,想法是显示每个计数从一个表上一个separete div

<div class="container">
     <p><strong><%= count %></strong> others. </p>
     <p><strong><%= count2 %></strong> others. </p>
</div>

jtjikinw

jtjikinw1#

1.答案如下

app.get("/", function(req, res, html){
    var q = "SELECT COUNT(*) FROM section1) AS count, (SELECT COUNT(*) FROM section1) AS count2"; //count first table

    let count, count2        
    connection.query(q, function(err, results){
    if(err) throw err;
    //count the results
    count = results[0].count; 
    count2 = results[0].count2;
    res.render('home', { count: count, count2: count2 }) 
});

字符串

wi3ka0sx

wi3ka0sx2#

app.get("/", function(req, res){
            // Find count of users in DB
            var q = "SELECT COUNT(*) AS count FROM section1"; //count first table
            var q2 = "SELECT COUNT(*) AS count2 FROM section2"; //count second table
    let count, count2        
    connection.query(q, function(err, results){
                if(err) throw err;
        
                 count = results[0].count; //i want to count table1
                
        
                //send values to html in different divs as count and count2
                  
            }); 
setTimeout(()=>{
            connection.query(q2, function(err, results){
                if(err) throw err;
        
           
                count2 = results[0].count; // I want to count table2
        
                //send values to html in different divs as count and count2
                
            });  
        res.render('home', { count: count, count2: count2 }) 
},4000)
        });

字符串

相关问题