2

I am making a string that is being used in a SQL statement. I need to reuse the same string within it several times. This string is the text from a textbox.

Current Code:

NSString *searchStr = [NSString stringWithFormat:@"(Name LIKE \'%%%@%%\' OR Contact LIKE \'%%%@%%\')", [self.txtfSearch text], [self.txtfSearch text]];

All the %'s are for a contains search. Please no comments on this method as I am connecting to a webservice that I have no control over currently. Im sure you can all relate.

What I need to do is reuse the [self.txtfSearch text] part at the end. I have looked up the apple dev docs on strings and placeholders. I even tried the C# method of using {0} for the placeholder but I cant get it working.

Doing it as above isnt a big deal if im looking in 2 columns, but there are many cases where its going to be 6 or more and then the string building gets ridiculous.

I want something like this:

NSString *searchStr = [NSString stringWithFormat:@"(Name LIKE \'%%{0}%%\' OR Contact LIKE \'%%{0}%%\')", [self.txtfSearch text]];

Is there a way to do this in obj-c?

John S
  • 573
  • 8
  • 22
  • 2
    You really shouldn't be building SQL strings like this. You're introducing an injection attack vector. – Brian Nickel Jul 29 '13 at 20:18
  • @BrianNickel I understand that but there is nothing I can do about it at this point as the service has been built already. I stated this in the OP. – John S Jul 29 '13 at 20:23
  • At least make an effort to properly escape the user's input before concatting SQL – Rob van der Veer Jul 29 '13 at 22:21
  • The database level security is its own thing. The problem I'm mentioning is what happens if the user types in `'`. – Brian Nickel Jul 29 '13 at 22:32
  • @BrianNickel I am escaping. Again, that is why I asked for no comments on that part. I dont need to show the code as it is not applicable to the question. – John S Jul 30 '13 at 14:11

1 Answers1

1

Could you do something like this:

NSString *placeholderStr = @"_";
NSString *searchStr = [@"(Name LIKE '%%_%%' OR Contact LIKE '%%_%%'" stringByReplacingOccurrencesOfString: placeholderStr withString: [self.txtfSearch text]];

This will replace all of the underscores (_) with whatever text is in txtfSearch.

Jason Barker
  • 3,020
  • 1
  • 17
  • 11
  • Might want to use something a little less common than an underscore, such as “THING_TO_REPLACE“. – Zev Eisenberg Jul 30 '13 at 02:49
  • @Zev If the template string itself could be modified by the user, it might be wise to use a combination of characters that the user wouldn't necessarily guess. However, if the template string is merely to be used internal to the app and won't be modified by the user, the underscore shouldn't be a problem at all. – Jason Barker Jul 30 '13 at 03:31
  • Good point. A random hash, perhaps even generated at runtime, could be a good placeholder. – Zev Eisenberg Jul 30 '13 at 03:47