Issue
I have an expressjs app of which I would like to count records from database in different or multiple tables and display the results on HTML on separate divs. The code is working with no errors but the issue is that I get the same result counted from one table to all the divs on my html page
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!");
});
and my html code, the idea is display each count from a table on a separete div
<div class="container">
<p><strong><%= count %></strong> others. </p>
<p><strong><%= count2 %></strong> others. </p>
</div>
Solution
- The answer is bellow
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 })
});
Answered By - Wylie
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.