0

throw err; // Rethrow non-MySQL errors ^

Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''a', 'b', 'c'' at line 1

(I had entered a as the name,b as the username and c as the password in the form)

I can't figure out where the problem is.

db.js:

function createUser(name, username, password){
    var sql = "INSERT INTO users (name,username,password) VALUES ?";
    var values = [name, username, password];
    con.query(sql, [values], function (err, result) {
      if (err) throw err;
      console.log('inserted');
    });
  }

  module.exports = {createUser};

relevant part of server.js:

app.post('/create', function(req,res) {
  db.createUser(req.body.name,req.body.username,req.body.password);
  res.status(200).send();
});
1
  • You nesting your values array inside another array. Commented Aug 29, 2020 at 21:22

2 Answers 2

1

I think you just need additional square brackets around the values:

var sql = "INSERT INTO users (name,username,password) VALUES ?";
var values = [[name, username, password]];
con.query(sql, [values], function (err, result) { ... });

This mechanism is mostly meant to insert multiple rows. You could also separate the parameters:

var sql = "INSERT INTO users (name,username,password) VALUES (?, ?, ?)";
var values = [name, username, password];
con.query(sql, values, function (err, result) { ... });
Sign up to request clarification or add additional context in comments.

2 Comments

The first one works, the second method gives the same error. Thanks though!
@jpj: the second code block should work too. Did you notice that I removed the square brackets around values in the query() call of the second code block?
0

You have to add for every variable a placeholder

function createUser(name, username, password){
    var sql = "INSERT INTO users (name,username,password) VALUES (?,?,?);";
    var values = [name, username, password];
    con.query(sql, values, function (err, result) {
      if (err) throw err;
      console.log('inserted');
    });
  }

  module.exports = {createUser};

Comments

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.