8

I'm making an apple app using phone gap (which uses sqlite database).

All my inserts work fine except for when I try to insert a weblink. This errors because there are " characters in the weblink.

Using the following:

var content = 'hello, this is my <a href="www.google.com">link</a>'
tx.executeSql('UPDATE PAGES SET content="'+content+'" WHERE id="1"');

Brings back the following error

error code 1
error: "near "http": syntax error"

If I remove the website address, I don't get an error. I have tried: content = escape(content);

but that hasn't worked.

Billie
  • 231
  • 6
  • 15

4 Answers4

11

Use parameter binding. This is the right and the safest way to do what you're trying to do.

tx.executeSql('UPDATE PAGES SET content=? WHERE id=1', [content]);
hamstergene
  • 24,039
  • 5
  • 57
  • 72
4

To escape quotes in SQLite you'll have to repeat the quotes.

So to insert a 7" screen you'll have to put a 7"" screen in the INSERT statement.

Dylan
  • 9,129
  • 20
  • 96
  • 153
1

The problem is the quote marks. They change the meaning of the SQL request and cause the error.

I can't find any information on escaping them properly. I read that you can put \ before them and then add ESCAPE ("\") to the SQL statement, but this doesn't seem to work with PhoneGap's implementation.

In the end, I did a simple replace, where single or double quote marks are replaced with &quot;, like so:

var thisNotes = $('textarea#notes').val().replace(/(["'])/g,'&quot;');

I just need to display quote marks in a text field however - I don't need them as part of a HTML link, so I'm not sure whether the link would still work. You may need to reverse the replace before displaying the link.

Hope this helps.

  • Then again, it seems a double quote mark may be a better answer, as per this [question](http://stackoverflow.com/questions/603572/how-to-properly-escape-a-single-quote-for-a-sqlite-database) – Stephen Cronin Jan 25 '12 at 11:54
  • So I've now revised my code to use .replace(/"/g,'""'). The single quotes seem to be fine, it's just the double ones and the above code fixes that. – Stephen Cronin Jan 25 '12 at 12:01
0

use javascript replace maybe create a function like so:

function CleanDbData( dirty ){
     var clean = dirty.replace( "/"","''").replace("<script>","[script]");
     return clean;
}

var mydata = CleanDbData( dirtydata );

this is not AS is, you will have to mess with regex etc but you get the idea [hopefully]

davethecoder
  • 3,856
  • 4
  • 35
  • 66