Safely inject SQL

How do I safely inject SQL queries in node red. I want to start with:

function addPost(body, username) {
return db.query(
INSERT INTO posts (body, username) VALUES (?, ?) ,
[body, username],
);
}

However I guess, i am missing something because it says cannot read query from undefined. Is there a good way to do a sanity SQL check in Node-Red?

That says that the variable db is undefined. Also I would have expected it to need a string parameter so it should be in quotes. Could you not use one of the SQL nodes rather than using javascript?

I am looking for a node or functions to prevent SQL injections into the database. I am already using node-red-node-mysql to insert the queries. I only want to know for sure the queries are safe.

I think if you use that syntax then mysql will sanitise the query for you, but I am not 100% certain of that. Your favourite search engine and the mysql docs should be able to confirm that.

1 Like

The safest thing to do is use a prepared statement. As these are parameterised, they are much harder to break.

https://dev.mysql.com/doc/refman/8.0/en/sql-syntax-prepared-statements.html