如何将变量插入到这行 SQL 代码中,或者有更好的方法吗?

问题描述 投票:0回答:1

我试图获取用户输入的国家/地区并检查该国家/地区的数据库,并找到其相应的国家/地区代码。然后,我将获取该国家/地区代码并将其插入到另一个表中。但是我不确定在这行特定的代码中我哪里出了问题。

这是我正在使用的整个代码部分:

app.post('/add', async (req, res) => {
  let userInput = [];
  userInput.push(req.body.country);
  console.log(userInput);
  userInput.forEach((country) => {
    const result = db.query(`SELECT country_code FROM countries WHERE country_name = ${userInput}`, function (err, result) {
      db.query('INSERT INTO visited_countries (country_code) VALUES ($1)',     [data.result] );
    });
    console.log(result);
    if (userInput) {
      const countries = db.query('SELECT country_code FROM visited_countries');
      result.row.forEach((countries) => {
        countries.push(country.country_code);
      console.log(result.rows);
    });
    res.render('index.ejs', {countries: countries, total: countries.length});
    }
  });
});

这是我正在尝试排除故障的部分:

const result = db.query(`SELECT country_code FROM countries WHERE country_name = ${userInput}`

console.log(结果)返回未定义

node.js postgresql http-post
1个回答
0
投票

不要将用户输入格式化为查询,而是使用绑定变量,就像您对

insert
语句所做的那样:

const result = 
    db.query('SELECT country_code FROM countries WHERE country_name = $1',
    [userInput],
    function (err, results) {
        // callback code...
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.