How do I parameterize a mySQL query so that the server selects from the database based off user input with nodejs?

51 views Asked by At

I have set up a simple local server that is connected to a mySQL database and it connects to the client and queries work but I need the query to work with a variable received from the client.

This is the server:

app.get('/data', async(req, res) => {
     var depart = req.query.dep;

     if (!depart) {
        return res.status(400).json({ error: 'Missing department parameter' });
     }

     var existsQuery = 'SELECT * FROM db.table WHERE department = ?';
     db.query(existsQuery, [depart], (err, result) => {
        if (err) throw err;
        console.log("result", result);
        res.json(result)
     });
});

The console log just prints [] instead of results from the database. Putting the query with a defined department number into mySQL gives results so I know that there are actual results that the server can get.

0

There are 0 answers