Running a SQL query like shown below. Here if the name is "Tim's Store" how do I escape it in my query below.
Most of the time the name variable will not have a ' but sometimes it does and I run into an error.
How do I escape this?
name = Tim's store
var sql = `INSERT INTO CHAT VALUES ('${id}', '${name}')`
DBconnection.query(sql)
In order to escape your name variable, you can first place the full string in double quotes and then list the apostrophe as you currently have it as shown here:
name = "Tim's store";
You can find another example of this here: https://www.digitalocean.com/community/tutorials/how-to-work-with-strings-in-javascript#using-the-alternate-string-syntax
And if you're attempting to escape any non-alphanumeric symbols as a means to stop hacking, you would need to use question mark place holders as noted here (pseudocode):
name = "Tim's store";
var sql = `INSERT INTO CHAT VALUES ( ? , ?)`
DBconnection.query(sql)
However, I've noticed that the post is tagged as working with javascript and SQL but the function after your sql query is a .NET function.
But, I'll stick to what the tags on the post stated (ie javascript). In order to have javascript (a client-side/front-end code) work with SQL (server side), you would first need to use NodeJs in order to work with SQL statement and escape your.
You would need to first use the code found on this page, https://www.geeksforgeeks.org/node-js-mysql-insert-into-table/ , to learn how to connect to your database with nodejs and then how to add an insert statement that's escaped using the question mark symbols as shown in the code examples.