I’m trying to use this to get contents of a specific table:
let tablename = req.body.login
connection.query('SELECT * FROM ?', tablename, (err, rows) => {
if (err) throw err
res.send(rows)
})
But due to tablename being a string, it gets inserted into the query with quotes, resulting in an error. If this can’t work, how can I structure my database to be able to add users and more data to any chosen one?
1
Using a raw SQL query, you can add the table name previous to the call of the query method, something like this:
let tablename = req.body.login;
let rawQuery = 'SELECT * FROM ' + tablename;
connection.query(rawQuery, (err, rows) => {
if (err) throw err
res.send(rows)
})
hope this helps.
You can just use template literal
using `
let tablename = req.body.login
connection.query(`SELECT * FROM ${tablename}`, (err, rows) => {
if (err) throw err
res.send(rows)
})
or simplifying more
connection.query(`SELECT * FROM ${req.body.login}`, (err, rows) => {
if (err) throw err
res.send(rows)
})