Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to write an SQL query that contains a NodeJS variable. When I do this, it gives me an error of 'undefined'.

I want the SQL query below to recognize the flightNo variable. How can a NodeJS variable be input into an SQL query? Does it need special characters around it like $ or ?.

app.get("/arrivals/:flightNo?", cors(), function(req,res){
var flightNo = req.params.flightNo;

connection.query("SELECT * FROM arrivals WHERE flight = 'flightNo'", function(err, rows, fields) {
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
339 views
Welcome To Ask or Share your Answers For Others

1 Answer

You will need to put the value of the variable into the SQL statement.

This is no good:

"SELECT * FROM arrivals WHERE flight = 'flightNo'"

This will work, but it is not safe from SQL injection attacks:

"SELECT * FROM arrivals WHERE flight = '" + flightNo + "'"

To be safe from SQL injection, you can escape your value like this:

"SELECT * FROM arrivals WHERE flight = '" + connection.escape(flightNo) + "'"

But the best way is with parameter substitution:

app.get("/arrivals/:flightNo", cors(), function(req, res) {
  var flightNo = req.params.flightNo;

  var sql = "SELECT * FROM arrivals WHERE flight = ?";
  connection.query(sql, flightNo, function(err, rows, fields) {
  });
});

If you have multiple substitutions to make, use an array:

app.get("/arrivals/:flightNo", cors(), function(req, res) {
  var flightNo = req.params.flightNo;
  var minSize = req.query.minSize;

  var sql = "SELECT * FROM arrivals WHERE flight = ? AND size >= ?";
  connection.query(sql, [ flightNo, minSize ], function(err, rows, fields) {
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...