2

I need to insert a record into mysql using nodejs. I am able to insert directly by typing values into the query just fine. I can insert using query + value syntax to concatenate the values but read this leaves open the risk of SQL injection.

        let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values ? ";
        var gametype ="Solo Zonewars";
        var teamSize =1;
        var maxPlayers = 16;
        var minPlayers = 10;
        var values = [gametype, teamSize, maxPlayers, minPlayers];

        console.log("connected as id '" + connection.threadId);
        
        connection.query(sql, values, function(err, result, fields) {
            connection.release();
            if(!err) {
                console.log(result);
            }else console.log(err);
        });    
        

Below is the attached error I am getting from mysql. It seems like it is putting extra quotes around the gametype variable and not attempting to insert the rest into the query. Any ideas? error from mysql

3 Answers 3

1

I would suggest you to not use an array and replace your query by this one

let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values (?, ?, ?, ?) ";

then you will pass the values one by one

Sign up to request clarification or add additional context in comments.

Comments

1

If you are having 4 value parameters to the query, you should have 4 question marks as well. Try with the first line changed to:

let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values (?, ?, ?, ?) ";

Comments

0

You can try wrapping your values into an array, as this method is intended for inserting multiple rows:

   let sql ="INSERT INTO gametypes (strGameType, intTeamSize, intMaxPlayers, intMinPlayers) Values ? ";
        var gametype ="Solo Zonewars";
        var teamSize =1;
        var maxPlayers = 16;
        var minPlayers = 10;
        var values = [
               [gametype, teamSize, maxPlayers, minPlayers]
        ];

    console.log("connected as id '" + connection.threadId);

    connection.query(sql, [values], function(err, result, fields) {
        connection.release();
        if(!err) {
            console.log(result);
        }else console.log(err);
    });    

Comments

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.