Reputation: 10799
I am using sqlite
in Objective-C via the C API. One of the intended features of my app is that the user can search for a person name and with each new character they enter, an SQL query using LIKE
is executed to find all people whose names qualify as a match. The issue I am running into is parameterizing the match inside the LIKE, without the question mark being interpreted literally. That is, I believe the app at present is looking for people's names that include ?
in them (which is nobody).
My code looks like this:
const char *sql = "SELECT rowid, name, email FROM person WHERE name LIKE '%?%'";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) {
NSLog(@"Problem preparing getFilteredPeopleStubs statement.");
}
if(sqlite3_bind_text(sqlStatement, 1, [searchText UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK){
NSLog(@"Problem binding search text param.");
}
Basically, searchText
is where I want the name to be coming from, but at the moment I believe it is just searching for people whose name contains ?
, because of the single quotations in '%?%'
. Is there a solution to this problem that still lets me use a parameterized query (protection against SQL injection) and achieves what I am after?
Upvotes: 5
Views: 2985
Reputation: 122391
Put the %
characters into searchText
, like (excuse the pun) this:
const char *sql = "SELECT rowid, name, email FROM person WHERE name LIKE ?";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare_v2(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) {
NSLog(@"Problem preparing getFilteredPeopleStubs statement.");
}
NSString *bindParam = [NSString stringWithFormat:@"%%%@%%", searchText];
if(sqlite3_bind_text(sqlStatement, 1, [bindParam UTF8String], -1, SQLITE_TRANSIENT) != SQLITE_OK){
NSLog(@"Problem binding search text param.");
}
Upvotes: 5