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.

4
  • Did you try using console.log to see how far it gets? Does it even reach the query? Commented Mar 25, 2014 at 23:52
  • 1
    You are only sending a response when thee is an error - add an else in to send a success response Commented Mar 25, 2014 at 23:53
  • Yes, it is reaching the query. @KeepCalmAndCarryOn it wouldn't be spitting out the error response if it worked! :P Commented Mar 25, 2014 at 23:58
  • @TidusSmith That changes everything. Did you try outputting the actual error instead of a generic message? Commented Mar 26, 2014 at 0:02

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

// get form values var post = { username : req.body.username, firstname : req.body.firstname, lastname : req.body.lastname };

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.