public class search {
public search(){
soql = '';
service = new list<Service__c>();
public string soql;
public string city{get;set;}
public list<Service__c> service{get;set;}
public void dosearch(){
 soql = '';
 soql = soql + 'select id,name,Bus_Type__c,From__c from Service__c';
 soql = soql + 'Where From__c = ' + '\''+city+'\'';
 system.debug('choos=================>' +soql);
 service = new list<Service__c>();
 service = database.query(soql);// Error hear


<apex:inputText value="{!city}"/>
<apex:commandButton value="Search" action="{!dosearch}"/> //Error
<apex:pageBlock title="Display Value">
<apex:pageblockTable Value="{!service}" var="v">
<apex:column value="{!v.name}"/>
<apex:column value="{!v.Bus_Type__c}"/>

1 Answer 1


you have problem with string query. Do not use string for SOQL query, until you have to do it, because dynamic SOQL is vulnerable to SOQL Injections. There are two ways to prevent possible SOQL Injections for dynamic queries:

  1. Use String.escapeSingleQuotes(String) method for your city parameter

public void dosearch(){ soql = 'select id, name, Bus_Type__c,From__c ' +'from Service__c ' +'where From__c = \''+String.escapeSingleQuotes(city)+'\''; service = Database.query(soql); }

  1. Use simple bind variables :city

public void dosearch(){ service = [ select id, name, Bus_Type__c,From__c from Service__c where From__c = :city ]; }

  • i need only dynamic i have requirement do another scenario
    – bingi
    Jun 10, 2017 at 17:55
  • @bingi I've updated my post above with dynamic query Jun 10, 2017 at 18:04
  • 1
    accept it if it helps you, so other users with same problem would have an answer Jun 10, 2017 at 19:44
  • +1 from me. Can you add a point to your answer about how it also avoids the SOQL injection risk?
    – Keith C
    Jun 11, 2017 at 10:03
  • @AlexanderBerehovskiy Sorry I wasn't clear: using either :city or String.escapeSingleQuotes(city) avoids the injection problem, with the former (that you had used) being cleaner. Was just asking for a mention of the risk as it is important to keep in mind with dynamic SOQL.
    – Keith C
    Jun 12, 2017 at 7:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .