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
Dilip Singh 1Dilip Singh 1 

SOQL Injection problem in dynamic query.

Hi Guys,
I am facing problem in soql injection, I have written a query to fetch Account data with condtion Name like bellow.
string queryString='select id,name,billingstreet from account'
if (AccountName != null && !AccountName.equals(''))    {
              AccountName= '%' + AccountName + '%';  
              queryString += ' Where Name LIKE :AccountName ';
     }
I have passed parameter % it's return all the account even I used String.escapeSingleQuotes(AccountName) as below
if (AccountName != null && !AccountName.equals(''))    {
              AccountName= '%' + String.escapeSingleQuotes(AccountName) + '%';  
              queryString += ' Where Name LIKE :AccountName ';
     }
Even it's return all account,

How can we resolve this Injection problem..
Thanks.

Best Answer chosen by Dilip Singh 1
logontokartiklogontokartik
You need to construct your query with actual values vs referencing a local variable in your dynamic SOQL. Something like below can resolve your issue.
string queryString='select id,name,billingstreet from account'

if (!String.isBlank(AccountName))    {
      queryString += ' Where Name LIKE \'%' + String.escapeSingleQuotes(AccountName) +  '%\'';'
}


 

All Answers

logontokartiklogontokartik
You need to construct your query with actual values vs referencing a local variable in your dynamic SOQL. Something like below can resolve your issue.
string queryString='select id,name,billingstreet from account'

if (!String.isBlank(AccountName))    {
      queryString += ' Where Name LIKE \'%' + String.escapeSingleQuotes(AccountName) +  '%\'';'
}


 
This was selected as the best answer
Dilip Singh 1Dilip Singh 1

Not working yet.

Thanks

sandeep@Salesforcesandeep@Salesforce
Hi Dilip,

I tried Kantik's solution. It is working at my end I did only few changes as below:
String AccountName;
string queryString='select id,name,billingstreet from account';

if (!String.isBlank(AccountName))    {
      queryString += ' Where Name LIKE \'%' + String.escapeSingleQuotes(AccountName) +  '%\'';
}
DataBase.query(queryString);

Thanks
Sandeep Singhal
http://www.codespokes.com/
Dilip Singh 1Dilip Singh 1
@Sandeep, yes I have used above code but when I passed charactor (%) in input box it return all the account.
Dilip Singh 1Dilip Singh 1
Thanks guys above code working for me. Thank you very much for your help.