Search code examples
javascriptnode.jsmysql2node-mysql2

mysql2 inserting values nodejs


I have this post request

app.post("/msg", (req, res) => {
  console.log(req.body)
  connection.query('INSERT INTO plans (topic, notes, resources) VALUES 
  (?)', [req.body.topic, req.body.note, req.body.resource],(error, 
  results) => {
     if (error) return res.json({ error: error });

     });
 });

and i get this error from it

"error": {
    "code": "ER_WRONG_VALUE_COUNT_ON_ROW",
    "errno": 1136,
    "sqlState": "21S01",
    "sqlMessage": "Column count doesn't match value count at row 1"
}

this is the table

CREATE TABLE plans(
  id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  topic VARCHAR(64) NOT NULL,
  notes VARCHAR(200) NOT NULL,
  resources VARCHAR(200) NOT NULL
 );

please whats wrong with the request ?


Solution

  • You have to provide the question mark according to number of column values you are providing.

    app.post("/msg", (req, res) => {
      console.log(req.body)
      connection.query('INSERT INTO plans (topic, notes, resources) VALUES 
      (?,?,?)', [req.body.topic, req.body.note, req.body.resource],(error, 
      results) => {
         if (error) return res.json({ error: error });
    
         });
     });
    

    this should work