3

Consider:

exports.adduser = function(connection) {
    return function(req, res) {

        // Get form values
        var username = req.body.username;
        var firstname = req.body.firstname;
        var lastname = req.body.lastname;

        var post = {
            username : username,
            firstname : firstname,
            lastname : lastname
        };

        connection.query('INSERT INTO myDatabase VALUES ?', post, function(err, result) {
            if (err) {
                res.send("There was a problem adding the information to the database.");
            }
        });
    }
}

This doesn't seem to work. Are there any glaring issues? Is the syntax correct? When I press the submit button on my form, it just hangs, and the insert never occurs. I have confirmed that the form gets the right values. The fields in the database table are username, firstname, and lastname.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
atkayla
  • 8,143
  • 17
  • 72
  • 132

1 Answers1

15

You misread the manual! If you are using an object to INSERT INTO you need to use SET:

INSERT INTO myDatabase SET ?

Quoting:

If you paid attention, you may have noticed that this escaping allows you to do neat things like this:

var post  = {id: 1, title: 'Hello MySQL'};
var query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {
  // Neat!
});
console.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'
TimWolla
  • 31,849
  • 8
  • 63
  • 96
  • `// get form values var post = { username : req.body.username, firstname : req.body.firstname, lastname : req.body.lastname };` – Randy Rebucas Nov 14 '19 at 10:56