Tyler Sears Tyler Sears - 1 month ago 4
MySQL Question

INSERT INTO query not working in Express.js

I'm having trouble inserting data into a MySQL database. Select queries work fine, so I'm assuming that it's something stupid that I've missed, either in the Express code, or, in my HTML. The page I'm running the query from is located at

localhost:8080/add
, and I'm trying to
INSERT INTO
. Here's my code:

Javascript

app.get('/add', function(req, res) {
res.sendFile(path.join(__dirname + '/Views/add.htm'));
});

app.post('/add', function(req, res) {
var fName = req.body.fName;
var email = req.body.email;
var id = req.body.id;
var post = {id: id, user: fName, email: email};
console.log(post);//This holds the correct data

connection.query('INSERT INTO user VALUES ?', post, function(err, result) {
if (!err) {
console.log('Successfully added information.');
} else {
console.log('Was not able to add information to database.');
}
});
});


My HTML is simply a submit button and 3 input fields, within in a
POST
method form. Again, I can connect to the database and read from it with a select query, I just cannot insert into it.

Answer

Look at the documentation here https://github.com/mysqljs/mysql#escaping-query-values.

connection.query('INSERT INTO posts SET ?', post, function(err, result) {
        if (!err) {
            console.log('Successfully added information.');
        } else {
            console.log(result);
            console.log('Was not able to add information to database.');
        }
});

Valid mysql statement is SET instead of Values.