简体   繁体   中英

Escape special characters in Javascript SQL Query

I'm trying to send an SQL query with javascript using a variable sourced from an input. In this input, characters like ' and " along with others may be entered.

Here's what my script function looks like:

function insertJobDesc (r) {
        rowid=r;
        var qty = document.getElementById('Qty' + r).value;
        var desc = document.getElementById('Desc' + r).value;
        desc = desc.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, '"&quot;"').replace(/'/g, '"&#039;"');

        sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
    }

An example of the value for 'desc' that I'd want to send is: 80-0234-1 6'5" GATE So it's a combination of numbers, letters, and special characters. I tried to replace each of them but it didn't work out.

Any ideas?

Use encodeURIComponent()

function insertJobDesc (r) {
    rowid=r;
    var qty = document.getElementById('Qty' + r).value;
    var desc = encodeURIComponent(document.getElementById('Desc' + r).value);

    sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
}

Disclaimer: Don't ever do anything like this...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM