Morsmetus
Morsmetus

Reputation: 63

Can not insert into mysql from node js

Sorry I just today started with Node.js and I may ask a newbie stuff but I have an error and I can't help it, I know I am doing something stupid but if you can help me I would be very thankful.

here is my code:

    var mysql = require('mysql');

    function BD() {
    var connection = mysql.createConnection({
        user: 'root',
        password: 'passHere',
        host: 'localhost',
        database: 'morsmetus'
    });
    return connection;
}



app.post("/index.html", function(req, res) {
    console.log("action");
    var objBD = BD();

    var post = {
        name: req.body.name,
        lname: req.body.lname,

    };

    objBD.query('INSERT INTO list SET ?', post, function(error) {
        if (error) {
            console.log(error.message);
        } else {
            console.log('success');
        }
    });
});
<form action="/index.html" method="POST">
  
<div><input name="name" type="text" class="cf_date" placeholder="Name"></div>
<div><input name="lname" type="text" class="cf_date"placeholder="Lname"></div>
  
<input type="submit" name="Submit" value="Submit" class="cs3_save" class="cs3_save">

</form>

;<

Upvotes: 0

Views: 1390

Answers (1)

Check the documentation of node_mysql

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'

Notice that they use SET instead of VALUES. INSERT INTO ... SET x = y is a valid MySQL query, while INSERT INTO ... VALUES x = y is not

Upvotes: 1

Related Questions