skip to Main Content

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?

2

Answers


  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.

    Login or Signup to reply.
  2. 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)
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search