SQL and SELECT using string varible

D

David G

Hello
When I use the following

NUM = 10
strSQL= "SELECT * FROM tblAds WHERE ID =" & NUM
Record comes up fine.

But when I use

NAME = "David"
strSQL= "SELECT * FROM tblAds WHERE NAME =" & NAME
I get error message.
Can someone help me?
Thanks,
David
 
J

Jim Buyens

-----Original Message-----
Hello
When I use the following

NUM = 10
strSQL= "SELECT * FROM tblAds WHERE ID =" & NUM
Record comes up fine.

But when I use

NAME = "David"
strSQL= "SELECT * FROM tblAds WHERE NAME =" & NAME
I get error message.
Can someone help me?
Thanks,
David

In a SQL statement, you must enclose character literals
in apostrophes. Here's an example.

strSQL= "SELECT * FROM tblAds WHERE NAME ='" & NAME & "'"

Here's a better example:

strSQL= "SELECT * " & _
"FROM tblAds " & _
"WHERE NAME ='" & Replace(NAME,".","''") & "'"

The second example is better because it doesn't blow up
if NAME happens to contain an apostrophe, such as O'Hara.
(SQL interprets double apostrophes as a literal value of
one apostrophe, and not as a delimiter. For example:

WHERE NAME = 'O''Hara'

searches for records containing O'Hara.

This also prevents a security risk called SQL Command
Insertion. In this exploit, the hacker submits a name
like this:

';DELETE FROM tblAds;

The apostrophe ends the literal, the semicolon ends the
SQL statement, and DELETE FROM tblAds removes all the
records from your table. Not kewl. But if you translate
the apostrophe to double apostrophes, the double
apostrophes don't end the literal.

Jim Buyens
Microsoft FrontPage MVP

http://www.interlacken.com
Author of:
*------------------------------------------------------*
|\----------------------------------------------------/|
|| Microsoft Office FrontPage 2003 Inside Out ||
|| Microsoft FrontPage Version 2002 Inside Out ||
|| Web Database Development Step by Step .NET Edition ||
|| Troubleshooting Microsoft FrontPage 2002 ||
|| Faster Smarter Beginning Programming ||
|| (All from Microsoft Press) ||
|/----------------------------------------------------\|
*------------------------------------------------------*
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top