I am new in node.js. I use Express and EJS. I want to select value from select option and based this value select data from Postgres database and render on-page. How can I do that? Here is my code:
EJS page
<select name="company" class="form-control" id="companylist" onchange="getselectedvalue();">
<% for (const comp of model1) { %>
<option value='<%= comp.ic %>'><%= comp.name %></option>
<% } %>
</select>
server.js
app.get("/users/dashboard",checkNotAuthenticated, (req, res) => {
const sql = `select * from company a join accountscompany b on a.id = b.id_company join accounts c on b.id_accounts = c.id WHERE c.id = $1`
pool.query(sql, [req.user.id], (err, com) => {
console.log(req.isAuthenticated());
res.render('dashboard', {user: req.user, content:"header", model1: com.rows});
});
});
So, for example: If I have to select value 1234 in select option value, then my query would be SELECT * FROM product WHERE company_ic = 1234
and render on my page.
Thanks for your help
You should create the pool outside of the app.get. I would suggest in its own file where you can then call on it as needed. I am assuming you are using the npm package mysql2
Also, I am assuming your sql syntax is correct. You did not give your table as reference.
require('dotenv').config();
const mysql = require('mysql2');
let pool = mysql.createPool({
host: "IP_ADDRESS",
user: "root",
password: process.env.DBPASSWORD,
database: "DBNAME",
waitForConnections: true,
connectionLimit: 20,
queueLimit: 0
});
const con = pool.promise();
module.exports = con;
then something like this before app.get
const bodyParser = require('body-parser')
const con = require('./mysqlPool.js')
app.use(bodyParser.urlencoded({ extended: true }))
Then in your function, you can do:
app.get("/users/dashboard",checkNotAuthenticated, async (req, res) => {
const com = await con.query('SELECT * FROM company a JOIN accountscompany b ON a.id = b.id_company JOIN accounts c ON b.id_accounts = c.id WHERE c.id = ?',[1234])
.then((result)=>{
return result[0];
});
res.render('dashboard', {user: req.user, content:"header", model1: com});
});
The 1234 is hard coded in the example above; however, you should obviously put in your req.query.[your variable name] variable in this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.