apex – Adding AND dynamic condition in SOQL

Use this in anonymous apex: (change objectname and recordtype as per your wish)

String objectName="dummy__c";
String searchText="%record%";
String recordType="koli";
String query= 'SELECT Id, Name, RecordType.developerName FROM ' +objectName+ ' WHERE Name LIKE: searchText AND RecordType.developerName =:recordType LIMIT 6';
system.debug(Database.query(query));

output something like:

DEBUG|(dummy__c:{Id=a0O5h00000NkqBEEAZ, Name=record 1, RecordTypeId=0125h000000zYnHAAU}, dummy__c:{Id=a0O5h00000NkqBJEAZ, Name=record 2, RecordTypeId=0125h000000zYnHAAU})

Explanation:
when you use colon(:) in dynamic query with respect to a variable, make sure to use the variable inside the string quotations (”).

If you want to use a Field of an object you can go with the method described in the question

Resource:Soql Injection

Hope this helps
solution:

public static List<sobject> findRecords(String searchKey, String objectName) { 
        string recordType="Tegal_Ent";
        string searchText="%"+searchKey+'%';  
        string query = 'SELECT Id, Name, RecordType.developerName FROM ' +objectName+ ' WHERE Name LIKE '+searchText+' AND RecordType.developerName =: '+recordType+' LIMIT 6';  
        return Database.query('SELECT Id, Name FROM ' +objectName+ ' WHERE Name LIKE: searchText AND RecordType.developerName =: recordType LIMIT 6');
}

Read more here: Source link