Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Active Server Pages (ASP)
Expertise: Beginner
Aug 26, 1999

Handling Single Quotes in Values From ASP

Question:
How can I prevent sending the contents of a form field containing single quotes to the server? Single quotes should be converted to double quotes in a way that doesn't give any problems when writing to the database.

Answer:

Just make sure that before you pass the data back to the database, you check the string for any improper values. One good way is to create a function called CheckString on your ASP page. This function would convert all occurrences of single quotes to two single quotes that should have no problem in your database. You can then call this function before passing the values to the database.

Function CheckString(byval strText)
   ' -- this function converts all single quotes
   ' -- inside 'strText' to two single quotes and
   ' -- also encloses the entire 'strText' string
   ' -- within single quotes

   CheckString = "'" & Replace(strText, "'", "''") & "'"
End Function

One problem with this code is that it relies on the VBScript Replace function to do the actual replacement. Memory leaks have occurred with the Replace function (hopefully they will be fixed in the future). If you do not wish to rely on the Replace function, you can use this second version of the CheckString function that does a brute force replacement.

Function CheckString(byval strText)
   Dim intPos
   intPos = InStr(strText, "'")
   While intPos > 0
      strText = Left(strText, intPos) & _
                "'" & _
                Mid(strText, intPos + 1)
      intPos = Instr(intPos+2, strText, "'")
   Wend

   CheckString = "'" & strText & "'"
End Function

Now, in your ASP page, assuming that you obtained the value of a form field into a variable called strAddress, you would "clean up" the variable before passing it over to the database.

   strAddress = CheckString(strAddress)

Note: If you do not want the CheckString function to enclose the string within single quotes, you can modify the code so it does not do so. Also, if you want single quotes to be replaced by any other character, you can modify the code to do so.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date