3

I want to do a simple insert with Node.js while I am using socket.io with node.js and MySQL. Don't know why, but I am geting this error

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''markos'' at line 1

My code:
When I try this, I get the above error.

io.on("connection", function(socket){
console.log("a user is connected " + socket.id );


    socket.on("question", function (question){

        let sql = "INSERT INTO nodeJs (name) VALUES ?";

        con.query(sql, question, function (err) {
            if (err) throw err;
            console.log("1 record inserted");
        });


    });

  });
});

if I try this simple code, everything works fine:

io.on("connection", function(socket){
console.log("a user is connected " + socket.id );


    socket.on("question", function (question){

        let sql = "INSERT INTO nodeJs (name) VALUES ('John')";

        con.query(sql, function (err) {
            if (err) throw err;
            console.log("1 record inserted");
        });

    });

 });
});

The question parameter always has a string.

2
  • 1
    Try this: let sql = "INSERT INTO nodeJs (name) VALUES (' + question + ')";. Note the simple quotes ' ' Commented May 10, 2021 at 11:22
  • 2
    In order to avoid sql injections i wouldn't recommend this.. Commented May 10, 2021 at 11:38

1 Answer 1

3

You're missing the parentheses around the values:

let sql = "INSERT INTO nodeJs (name) VALUES (?)";
// Here ------------------------------------^-^
Sign up to request clarification or add additional context in comments.

3 Comments

i just can't believe that i was missing this ! I still learning node.js and i was studying throw w3School w3schools.com/nodejs/nodejs_mysql_insert.asp . They are not putting parenthesis like you.. Anyway thank you very much for your time
@Markos yes there are parenthesis because mysql needs then
@Markos you skip parenthesis with this syntax only: INSERT INTO nodeJs SET name= ? where you also don't use single quotes around the quesiton mark

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.