skip to Main Content

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'
                });
            }
        })
    })
})

2

Answers


  1. 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',
        });
      }
    });
    
    Login or Signup to reply.
  2. your syntax typo, just change to

    let sql = `INSERT INTO news (Headline, Content) VALUES (${headline}, ${content})`;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search