1

How do I make the below code less vulnerable to SQL injection attacks? and also be able to accept " and ' characters in the parameters?

app.get('/addStudent',(req,res) => {
  const {fname, lname, othname, bloodType}= req.query;

  let sqlstmt = "INSERT INTO `students` (`fname`, `lname`, `othname`, `bloodtype`) VALUES ('"+fname+"', '"+lname+"', '"+othname+"', '"+bloodType+"')"
    db.query(sqlstmt,(err,result) => {
    if(err){console.log('Error occured while fetching user information',err)}
    console.log(result);
    res.send(result);
  });
});
Dworo
  • 153
  • 1
  • 4
  • 15

1 Answers1

2

You should use prepared statements which should be supported by your driver package for your chosen DBMS.

An example for MySQL: https://github.com/mysqljs/mysql#preparing-queries

Jannis Lehmann
  • 1,428
  • 3
  • 17
  • 31
  • 2
    Yes, but more to the point, use query parameters. Just doing a prepared statement from a string that has been formed with string-concatenation doesn't magically make it safe. – Bill Karwin Mar 27 '20 at 16:05
  • how can I modify my above code using query parameters and prepared statements? – Dworo Mar 28 '20 at 06:35