0

In the SQL query where city clause when I put string 'delhi' I get results but when I put a variable like below I get error unknown column delhi in where clause. how to solve the issue?

router.get('/filter/:city', (req, res) => {
  const location = req.params.city;
  const singleQuoteLocation = location.replace(/"/g, "'");
  connection.query(
    `select * from weather_data where city=${singleQuoteLocation}`,
    (err, results, field) => {
      if (err) {
        console.log(err);
      } else {
        res.status(200).send(results);
        console.log(results);
      }
    }
  );
});
2
  • what will be the output if you put console.log(singleQuoteLocation) // Delhi or 'Delhi' Commented Dec 24, 2021 at 6:51
  • 1
    before connection.query... store your query string in a variable and print that in console.: select * from weather_data where city=${singleQuoteLocation} then you will see what's wrong with your formed query. Commented Dec 24, 2021 at 6:52

2 Answers 2

2

You should be using a prepared statement with a ? placeholder for the city value. Then, bind a JS variable to the ?.

router.get('/filter/:city', (req, res) => {
  const location = req.params.city;
  connection.query(
    "SELECT * FROM weather_data WHERE city = ?", [location],
    (err, results, field) => {
      if (err) {
        console.log(err);
      }
      else {
        res.status(200).send(results);
        console.log(results);
      }
    }
  );
});

Note that when using a prepared statement there is no need to massage the location variable by doing things like wrapping in single quotes. Instead, let your MySQL driver worry about how to handle this, via the prepared statement.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked but can you elaborate more like where I can find the syntax or share a helpful reference about this problem. and one more question how can I put 2 variables in the query?
Check here. You may use as many ? placeholders as you like, but ? can only appear where literal values would otherwise appear. That is, you can't use ? for things like column and table names.
0
`select * from weather_data where city = \'${singleQuoteLocation}\' `

2 Comments

what this backslash does
it will ignore quotes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.