3

So basically, I have this JavaScript variable which stores this certain value, and I need to put this variable in MySQL Query statement.

Source Code:

var Pollution_Reading = 25;
DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('"Pollution_Reading"')');

I've tried every way that I know, but I still can't insert the value that the variable is holding into the database. What should I do?

4 Answers 4

3
DatabaseConnection.query('INSERT INTO Air_Pollution_Record (Air_Pollution_Reading) VALUES ('+Pollution_Reading+')');
Sign up to request clarification or add additional context in comments.

1 Comment

Be careful with the inserted data, if it is data sent by the user, then it is better to escape query values to avoid sql injection ​​using mysql.escape() or in another way: npmjs.com/package/mysql#escaping-query-values
3

Try doing this:

//reading  post data
const useremail = req.body.useremail;
const password = req.body.password;
//save into db start
var sql = "INSERT INTO `users` (`UserName`, `UserPassword`) VALUES ('"+useremail+"','"+ password+"')";

Comments

3

you can try this format of template literals. Gives you Easy and Clean code.

const sql = `INSERT INTO query_form (name, email, query_title, query_description) VALUES ('${name}', '${email}', '${query_title}', '${query_description}')`;

Comments

2

const sql = "INSERT INTO users (UserName, UserPassword) VALUES ('"+useremail+"','"+ password+"')";

This method and also above are good but naive if you have quotes in your input variable like single or double quotes. It will match the single quote with the input string and you will get error as it will not consider the remaining input.

So, after a long painful research I found a fix for quotes input strings as well. The solution is to not use values front hand and pass them inside con.query() method directly.

let query = `INSERT INTO gfg_table 
        (name, address) VALUES (?, ?);`;
  
    // Value to be inserted
    let userName = "Pratik";
    let userAddress = "My Address";
  
    // Creating queries
    db_con.query(query, [userName, 
    userAddress], (err, rows) => {
        if (err) throw err;
        console.log("Row inserted with id = "
            + rows.insertId);
    });

Reference:

https://www.geeksforgeeks.org/node-js-mysql-insert-into-table/

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.