Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

on most of our pages, we have some url parameters. we use these parameters as bind variables in various SOQL queries. is there a common pattern we can use which takes care of security issues.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

Using bind variables automatically takes care of all SOQL injection vulnerabilities, with no extra effort on the part of the developer. You should always use bind variables on any untrusted or unsanitized user input. You can even use simple bind variables on dynamic queries to avoid having to manually escape special characters.

String query = 'select id, name from lead where name = :leadName';
Lead[] records = Database.query(query);

You can't evaluate Apex Code in dynamic queries, though, so that means you can't use something like:

String query = 'select id, name from lead where id in :leads.keySet()';

You can reference a set or list, but you can't reference a single element in a list, for example. If you need to use page parameters from a Visualforce page, for example, you'll have to pull them out into individual variables that you can reference, if you're using dynamic queries.

String searchName = ApexPages.currentPage().getParameters().get('name');
String query = 'select id, name from lead where name = :searchName';
Lead[] records = Database.query(query);

For inline queries, you can inline complex code if you desire:

Lead[] records = [select id, name from lead 
                  where name = :ApexPages.currentPage().getParameters().get('name')];
share|improve this answer
    
well said. if I remember correctly, if searchname was an object variable (instead of a method variable), even this.searchName won't work a a bind variable - no dot notation permitted. –  crop1645 yesterday
    
@crop1645 You can't use this.searchName, but the entire scope is available to you, so you can use searchName so long as it is a function variable or member variable. See example: class A01 { String bind = 'test'; void execute() { Contact[] records = Database.query('SELECT Name FROM Contact WHERE Name = :bind'); } } new A01().execute(); (execute anonymous window) The only rule is that no evaluation is allowed, so you get only simple variable scope. –  sfdcfox yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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