0

Socket.io, Node.js: How can a javascript variable be passed to mysql query from in a javascript.js?

There is an error when a variable of value '222.222.222.222', is attempted to be passed into the mysql query, but not when a variable having a value of '2' is passed into the same mysql query.

Any help would be greatly appreciated.

This gives error:

var javascriptVariable = '222.222.222.222';

$query = 'INSERT INTO misc_table (misc_field) VALUES ('+javascriptVariable+')';

connection.query($query, function(err, rows, fields) {
if(err){
    console.log("An error ocurred performing the query.");
    return;
    }
    console.log("Query succesfully executed: ", rows);
    });

This does not give error:

var javascriptVariable = '2';

$query = 'INSERT INTO misc_table (misc_field) VALUES ('+javascriptVariable+')';

connection.query($query, function(err, rows, fields) {
if(err){
    console.log("An error ocurred performing the query.");
    return;
    }
    console.log("Query succesfully executed: ", rows);
    });

4
  • $query = 'INSERT INTO misc_table (misc_field) VALUES ('+javascriptVariable+')'; :) Commented Jun 7, 2020 at 15:12
  • This is kinda really basic just try to go over js basics again i'm guessing you need some problems there .😊 Commented Jun 7, 2020 at 15:13
  • Edited the question, but still not working. There is an error: An error ocurred performing the query. Commented Jun 8, 2020 at 1:27
  • Oh aight i saw you get your answer and it's better to use it that way bdw. Thx @Vasyl Moskalov Commented Jun 9, 2020 at 8:04

1 Answer 1

2

Never ever thought to update databases in this manner. First. In fact, you try to execute next code

INSERT INTO misc_table (misc_field) VALUES (222.222.222.222)

Second. This is the straight way to sql injection

Thrid. Try something like this

var javascriptVariable = '222.222.222.222';

let $query = 'INSERT INTO misc_table (misc_field) VALUES (?)';
connection.query(
    $query,[ javascriptVariable ], 
    function (...args) {
....
    }
);
Sign up to request clarification or add additional context in comments.

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.