Rafik Bari
Rafik Bari

Reputation: 5037

How to escape special characters like " in the SQL query in order to avoid Injection

Using delphi 2010, i am wondering if there someway to escape the following string to make it safe from sql injection attacks :

my string :

    SQLQuery1.SQL.Text := 'SELECT * FROM registered WHERE email="'+
      email+'" and login_pass="'+password+'"';

How to rewrite this string, to make it safer than it is when someone type " in my TEditbox as his email or password !

Upvotes: 5

Views: 9516

Answers (3)

HeartWare
HeartWare

Reputation: 8261

If for whatever reason you can't use parameters, you can use a function like this:

USES SysUtils;

FUNCTION QuotedStr(CONST S : STRING) : STRING;
  BEGIN
    Result:='"'+ReplaceStr(S,'"','""')+'"'
  END;

and then

SQLQuery1.SQL.Text := 'SELECT * FROM registered WHERE email='+
  QuotedStr(email)+' and login_pass='+QuotedStr(password);

(this assumes that your database provider uses double quotes to delimit strings with and that two consecutive double quotes in a quoted string is really a single double quote, ie. one double quote).

Upvotes: -1

Uri Goren
Uri Goren

Reputation: 13700

the basic replacement of ' with '' should make sure that you won't get injected in textual fields.

As a rule of thumb, make sure all inputs you add to the database are in the pattern you expect them to be. in the case of email addresses, zip codes and passwords- you can define a simple regex to verify the validity.

keep in mind, that numeric fields can be also injected and should be verified as well.

Upvotes: 0

Ken White
Ken White

Reputation: 125757

Use parameters, and let the database drivers handle that stuff.

SQLQuery1.SQL.Text := 'SELECT * FROM registered WHERE email= :email'+
  ' and login_pass = :password';
SQLQuery1.ParamByName('email').AsString := EMail;
SQLQuery1.ParamByName('password').AsString := Password;

Upvotes: 14

Related Questions