7

I have a query string that is as follows(no bulkification required)...

 String qryString = 'SELECT Id FROM Contact WHERE (IsDeleted = false and Name like \'%' + searchText+ '%\')';

searchText is a text input field. This code is prone to SOQL Injection because of the apostrophe. So how to make it safe?

Any suggestions will be helpful.

9

There's a Salesforce help article that addresses this..

The main point's are:

  • Avoid using dynamic SOQL where possible, instead use static queries and binding variables
  • If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input.

Here is an example of moving from a dynamic query to a static query with binding variables:

Dynamic Query

public class SOQLController {
    public String name {
        get { return name;}
        set { name = value;}
    } 
    public PageReference query() {
        String qryString = 'SELECT Id FROM Contact WHERE ' +
        '(IsDeleted = false and Name like \'%' + name + '%\')';
        queryResult = Database.query(qryString);
        return null;
    }
}

Static Query

public class SOQLController { 
    public String name { 
        get { return name;} 
        set { name = value;} 
    } 
    public PageReference query() { 
        String queryName = '%' + name + '%';
        queryResult = [SELECT Id FROM Contact WHERE 
           (IsDeleted = false and Name like :queryName)];
        return null; 
    } 
} 
  • 2
    Can you add a bullet point to say "use simple bind variables" in dynamic SOQL? The documentation isn't great but binding works for dynamic SOQL as well for simple cases and offers the same SOQL injection defence benefits as it does in static SOQL. – Keith C Jun 23 '14 at 8:13
  • Yes it does nick. Thanks. @KeithC can you please explain what is "use simple bind variables". Does it mean using static query? – MnZ Jun 23 '14 at 8:21
  • 3
    @MnZ No it means you can bind a variable such as a string or a date or a decimal into the dynamic SOQL using the :myVarName syntax. You can't (directly) bind a dotted expression such as mySob.MyField__c; instead you first have to assign that to a simple variable String myVarName = mySob.MyField__c and then bind the simple variable. – Keith C Jun 23 '14 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.