function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
big bangbig bang 

How to deal with SOQL injection when use dynamic search

Dears,

 

I have a search page with several conditions, I pass the conditions to controller and make my search soql like this:

String soql = 'select Id , Name from Account where';
if (a != null) {
    soql += ' and xxx__c = \'' + a '\''
}
if (b != null) {
    soql += ' and yyy__c = \'' + b '\''
}
......
List<Account> accList = Database.query(soql);

It seems like cannot pass the security scan because this is a soql injection.(Well, I just heard about that, I don't know whether this really cannot pass the scan...)

 

I read the wiki and other documents, they just say you should use static soql to put the parameters, like this:

PreparedStatement query = "select * from users where userid = :user and password = :password";
query.bindInt("user", Request.form("user").intValue());
query.bindString("password", getSaltedHash(Request.form("password")));
Database.executePreparedStatement(query);

But in my situation, I need to make the where clause dynamicly.

Is there some solutions to deal with it?

Waiting for your answers.

Thank you.

Best Answer chosen by Admin (Salesforce Developers) 
asish1989asish1989

String soql = 'select Id , Name from Account where';
if (a != null) {
soql += ' and xxx__c = \'' + String.escapeSingleQuotes(a) +'\''
}
if (b != null) {
soql += ' and yyy__c = \'' + String.escapeSingleQuotes(b)+ '\''
}
......
List<Account> accList = Database.query(soql);

All Answers

Abhi_TripathiAbhi_Tripathi

The thing you are trying is in this blog...take a look

 

http://abhithetechknight.blogspot.in/2013/07/dynamic-soql-brief-description.html

 

Thanks

Abhi

asish1989asish1989

String soql = 'select Id , Name from Account where';
if (a != null) {
soql += ' and xxx__c = \'' + String.escapeSingleQuotes(a) +'\''
}
if (b != null) {
soql += ' and yyy__c = \'' + String.escapeSingleQuotes(b)+ '\''
}
......
List<Account> accList = Database.query(soql);

This was selected as the best answer
Avidev9Avidev9
Well there are is more elegant way to use variables in SOQL. Have a look here http://blogforce9.blogspot.in/2012/08/using-variables-in-dynamic-soql.html
big bangbig bang

Nice.

It seems like I just need some escapes.

 

Thanks.