Home > OS >  MySQL saving issue node
MySQL saving issue node

Time:10-14

I’m setting up a subdomain where users can upload updates to the database.

The correct data gets sent from the front end, and the API connects to the database successfully but stops there. I can’t figure out why.

app.post('/newsupdate', (req, res) => {
    let headline = req.body.headline;
    let content = req.body.content;

    let con = mysql.createConnection({
        host: HOST,
        user: USERNAME,
        password: PASSWORD,
        database: DATABASE
    });

    con.connect(function(err){
        if(err) return res.json({
            message: err
        });
  
        let sql = `INSERT INTO news (Headline, Content) VALUES (${headline}, &{content})`;
  
        con.query(sql, function(err, result){
            if(err) return res.json({message: err});

            if(result){
                res.json({
                    message: 'news update saved'
                });
            } else {
                res.json({
                    message: 'problems happened'
                });
            }
        })
    })
})

CodePudding user response:

You have a typo in your query (&{content}), try to use a prepared statement as suggested:

let sql = `INSERT INTO news (Headline, Content) VALUES (?, ?)`;

con.query(sql, [headline, content], function (err, result) {
  if (err) return res.json({ message: err });

  if (result) {
    res.json({
      message: 'news update saved',
    });
  } else {
    res.json({
      message: 'problems happened',
    });
  }
});

CodePudding user response:

your syntax typo, just change to

let sql = `INSERT INTO news (Headline, Content) VALUES (${headline}, ${content})`;
  • Related