2

I've search around but not found an answer to this one.

Is there a function in Javascript similar to PHP's mysql_real_escape_string to make safe user inputs before writing them to a WebSQL database?

If not, does anyone know of a custom made function out there that I could use?

UPDATE: So it seems like there is no native function, so I have written:

function sql_real_escape_string(val){
    var val = val.replace('"','"');
    val = val.replace('\'','’');
    return val;
}

Are there any other characters that I should be replacing to be on the safe side?

Fraser
  • 14,036
  • 22
  • 73
  • 118
  • WebSQL is deprecated and work was stopped on the spec 2 years ago. You should use [Indexed DB](http://en.wikipedia.org/wiki/Indexed_Database_API) instead. – josh3736 Jul 22 '12 at 02:06
  • 3
    He did use the "phonegap" and "cordova" tags, so I'm thinking Indexed DB is not an option as there's no support on Android or iOS. I'd definitely agree with you otherwise. – Zach Shipley Jul 22 '12 at 02:15

1 Answers1

5

The best answer to handling user input when inserting into databases is to employ paramaterization. The Web SQL API supports this:

var db = openDatabase('mydb', '1.0', 'my database', 2 * 1024 * 1024);
db.transaction(function (tx) {
  tx.executeSql('INSERT INTO foo (id, text) VALUES (?, ?)', [id, userValue]);
});

Instead of this:

db.transaction(function (tx) {
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "user-entered value")');
});
Zach Shipley
  • 1,092
  • 6
  • 5
  • I'm new to this Phonegap malarky. I've amended my code and will be doing this in future though. Thanks for the heads up. – Fraser Jul 22 '12 at 02:30