-1

I'm trying to search the text entered by the user in the searchbar to check if that text is contained by any of the database entries and want to store the result into a NSMutableArray

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [search resignFirstResponder];
    [search endEditing:YES];

    str = search.text;

    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    app.databasePath = [app getDBPath];
    const char *dbpath = [app.databasePath UTF8String];
    sqlite3_stmt *statement;

    if (sqlite3_open(dbpath, &conn) == SQLITE_OK)
    {
        NSString *strSelectQuery = [NSString stringWithFormat: @"SELECT songname FROM Songs WHERE songname LIKE '%%@%'", str];

        const char *query_stmt = [strSelectQuery UTF8String];

        if (sqlite3_prepare(conn, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                [matchList addObject:[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]];
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(conn);
    }
    NSLog(@"Total Songs : %i", [matchList count]);
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Vaibhav Jhaveri
  • 1,579
  • 3
  • 28
  • 53

1 Answers1

0

The above code didn't work because i Forgot to write a Line which reloads the data after i have entered the text and clicked on the Search button of the UISEarchBar

[_searchResultTable reloadData];

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [search resignFirstResponder];
    [search endEditing:YES];

    str = search.text;

    songList = [[NSMutableArray alloc] init];

    app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    app.databasePath = [app getDBPath];
    const char *dbpath = [app.databasePath UTF8String];
    sqlite3_stmt *statement;

    if (sqlite3_open(dbpath, &conn) == SQLITE_OK)
    {
        NSString *strSelectQuery = [NSString stringWithFormat: @"SELECT * FROM Songs WHERE songname LIKE '%%%@%%'", str];
        const char *query_stmt = [strSelectQuery UTF8String];

        if (sqlite3_prepare(conn, query_stmt, -1, &statement, NULL) == SQLITE_OK)
        {
            while (sqlite3_step(statement) == SQLITE_ROW)
            {
                [songList addObject:[[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]];
            }
            sqlite3_finalize(statement);
        }
        sqlite3_close(conn);
    }

    [_searchResultTable reloadData];
}
Vaibhav Jhaveri
  • 1,579
  • 3
  • 28
  • 53
  • It would be useful to future readers if you included some comments (in the code or separately) that explained what you are doing and why your original solution did not work. – Hot Licks Sep 13 '14 at 12:18
  • 1
    It also needs to be noted that you've set yourself up for a "SQL injection" hack. – Hot Licks Sep 13 '14 at 12:19