0

How I am performing a SQL query to insert data into the database. Note that the field PlanDetails in the table dbo.Plans is a text field. However, when a user tries to input a sentence which contains an apostrophe (e.g. I'll go to sleep). via the HTML form . The database returns an error "Incorect syntax near ll), which refers to the apostrophe problem. In this case, how should I modify the code below to make it accept sentences with apostrophe? It is told that I can use parameterized queries. In this node js example, how can I do that?

CreatePlan : function (newPlan , UserID, DisplayName, Email, callback) {
    var sql = require('mssql');
    var config = require('./configuration/sqlconfig');
    var conn = new sql.Connection(config);
    var req = new sql.Request(conn);
    conn.connect(function (err) {
        if (err) {
            console.log(err);
            return;
        } 
        console.log('Attempting to Insert new learning plan...');
        req.query('INSERT INTO dbo.Plans (PlanTitle, PlanTopic, OwnerID, OwnerName, PlanDetails, TargetLearners, OwnerContact) VALUES ("' + newPlan.PlanTitle + '", "' + newPlan.PlanTopic + '", "' + UserID + '", "' + DisplayName + '", "' + newPlan.PlanDetails + '", "' + newPlan.TargetLearners + '", "' +Email+ '");', function (err) {
            if (err) {
                console.log(err);
            } else {
                console.log("Added one new learning plan");
                console.log("The new plan title is " + newPlan.PlanTitle);
                callback();
            }
            conn.close();
        });
    });
},
Grayson Ho
  • 35
  • 5

1 Answers1

0

In SQL (and in many other languages), you have to escape special characters to avoid any ambiguity in the code. There is a lot of documentation about how to escape and which character are concerned all other internet.

Here is the wikipedia article about escape character: https://en.wikipedia.org/wiki/Escape_character

Here is a stackoverflow post that answer your question: How do I escape special characters in MySQL?

However I should warn you about SQL injection, the code you are using will not be safe and you should probably take a look at the good practice in this matter.

Community
  • 1
  • 1
Sylvain
  • 417
  • 7
  • 16
  • Can you also share a source which I can learn how to use parameterized SQL queries in Node JS? Thanks!! – Grayson Ho Apr 03 '17 at 10:23
  • I'm pretty sure you got everything you need to do it yourself. (also I never used SQL on node so I'm not better than you an this subject) – Sylvain Apr 03 '17 at 10:27