Go Back   CodingForums.com > :: Server side development > ASP

Before you post, read our: Rules & Posting Guidelines

Closed Thread
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-15-2002, 12:13 AM   PM User | #1
whammy
Senior Coder

 
Join Date: Jun 2002
Location: 41° 8' 52" N -95° 53' 31" W
Posts: 3,660
Thanks: 0
Thanked 0 Times in 0 Posts
whammy is an unknown quantity at this point
Single Quotes give me a syntax error!

Ok, since this question is asked very frequently, I decided to post this sticky thread.

Many developers new to ASP and SQL find out that they get a syntax error when inserting a record into a database where the user's input (or the variable itself perhaps) contains a single quote.

In SQL, you can keep this from erroring by escaping a single quote with another one., i.e.:

Code:
myvar = "Bob's Diner"

SQL = "INSERT INTO tablename (myvar) VALUES ('" & myvar & "')"
Set rs = Conn.Execute(SQL)
Will throw an error, since there is a single quote in the variable.

The easiest way to solve this is to just comment out the quote with another:

Code:
myvar = "Bob's Diner"

SQL = "INSERT INTO tablename (myvar) VALUES ('" & Replace(myvar,"'","''") & "')"
Set rs = Conn.Execute(SQL)
However, as you can see, that can get really messy if you're using a lot of variable that can potentially contain a single quote. In order to get around this, just create a function, and ONLY use it when inside a SQL statement (so you don't end up with multiplying single quotes in your data). i.e.:

Code:
Function CSQ(byVal str)
     If IsNull(str) Then str = ""
     CSQ = Replace(str,"'","''")
End Function

myvar = "Bob's Diner"

SQL = "INSERT INTO tablename (myvar, myvar2) VALUES ('" & CSQ(myvar) & "','" & CSQ(myvar2) & "')"
Set rs = Conn.Execute(SQL)
In the above code, "CSQ" stands for "Comment Single Quotes"... but you can name the function whatever suits your fancy.

Hope this helps!

__________________
Former ASP Forum Moderator - I'm back!

If you can teach yourself how to learn, you can learn anything. ;)
whammy is offline  
Closed Thread

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 04:28 AM.


Advertisement
Log in to turn off these ads.