how to make login page in iphone using sqlite - iphone

I am trying to create to create login page in iPhone using sqlite.
I need suggestions ,how to create login form with username /password authentication. For successful login - user should navigate to next page like UITableview.Otherwise giving user a error message: login failed. Please help me. I am new to the Programming.

First you create registration page and after this code apply in your login view..
if([uername.text isEqualToString:#""] || [password.text isEqualToString:#""]) {
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Here comes a block." message:#"You missed something, please check your details and try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
//insert data
NSString *query=[NSString stringWithFormat:#"select * from registration_table where username=\"%#\" and password=\"%#\"",uername.text,password.text];
NSLog(#"%#",query);
//select * from registration_tbl where username="d" and password="d"
array=[app.sk lookupAllForSQL:query];
NSLog(#"%#",[array description]);
if (array.count>0)
{
app.currrentid=[[array objectAtIndex:0]objectForKey:#"uid"];
NSLog(#"%#",app.currrentid);
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"" message:#"login successful" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
messageviewcontroller *log = [[messageviewcontroller alloc]initWithNibName:#"messageviewcontroller" bundle:nil];
[self.navigationController pushViewController:log animated:YES];
[log release];
log.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:log animated:YES];
}
else
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Here comes a block." message:#"angry" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
uername.text=#"";
password.text=#"";
//push the view
}
i hope this code useful for you.

Create a table for storing username and password
Input the value such that password is encrypted.
Make a login page with Textfield for username and password
On button action collect the username and password from textfield
.
-(IBAction)loginbuttonPressed:(id)sender
{
if (check username is in table == success)
{
//encrypt the password entered compare and check for password is true for the username in table
if(check password is in table= password found success)
{
// Successfully logged in
}
else
{
//alert "Password Incorrect"
}
}
else
{
// Alert "Username not found"
}
}

First of create 1 sample database with User Table with UserName & Password fields.
Then, copy database into application while installing first time.
- (void) copyDatabaseIfNeeded
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
dbPath = [self getDBPath];
BOOL success = [fileManager fileExistsAtPath:dbPath];
if(!success)
{
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"dbSample.sqlite3"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:&error];
if (!success)
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
/********* Database Path *********/
- (NSString *) getDBPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:#"dbSample.sqlite3"];
}
Then, check on Validate Button Click,
-(IBAction)validateUser:(id)sender
{
if (sqlite3_open([[appDel getDBPath] UTF8String], &dbTest) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT UserName, Password FROM tblUser Where UserName = \"%#\"",[txtUserName text]];
NSLog(#"%#",querySQL);
const char *sql = [querySQL UTF8String];
sqlite3_stmt *searchStatement;
if (sqlite3_prepare_v2(dbTest, sql, -1, &searchStatement, NULL) == SQLITE_OK)
{
if (sqlite3_step(searchStatement) == SQLITE_ROW)
{
infoUserName = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(searchStatement, 0)];
infoUserPassword = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(searchStatement, 1)];
NSLog(#"User : %#, Password : %#",infoUserName, infoPassword);
}
}
sqlite3_finalize(searchStatement);
}
sqlite3_close(dbTest);
}
May be, it'll help you.
Thanks.

First thing you need to do is add libsqlite3.dylib to your list of frameworks.
As a Second thing you should start reading the SQLite3 documentation, especially the five-minute guide. If you want some reference to understand how to "Save Data to the SQLite Database" and "Extract Data from the SQLite Database" , you can always check the Beautiful Tutorial : An Example SQLite based iPhone Application
Third and Most Importing thing you need to do is : Read Above Links ( Reference to Line in your Question I AM new to the Programming ).
At last, I cans say you : Good Luck !!!

Related

how to save the tabledata in sqlite in iphone

i am trying to store the data in table using sqlite manager.But the values are not stored in database.If i click the save button the error message will be displayed on like this Failed to open/create database. I cant understand how to solve the problem.Anybody please give me an idea how to solve this problem.Thanks in advance.
DBManager.m
-(BOOL)createDB {
NSString *docsDir;
NSArray *dirPaths;
// Get the document directory
dirPaths=NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask,YES);
docsDir=dirPaths[0];
// Build the path to the database file
databasePath=[[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:#"Feedback.db"]];
BOOL isSuccess=YES;
NSFileManager *fileManager=[NSFileManager defaultManager];
if([fileManager fileExistsAtPath:databasePath]==0) {
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &database)==SQLITE_OK) {
char *errMsg;
const char *sql_stmt= "create table if not exists Feeback details (Traineeid integer, Trainername text,Traineename text,Rating float)";
if(sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)!=SQLITE_OK) {
isSuccess=NO;
NSLog(#"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess=NO;
NSLog(#"Failed to open/Create database");
}
}
return isSuccess;
}
// save data in the Database
-(BOOL) saveData:(NSString *)Traineeid Trainername:(NSString *)Trainername Traineename:(NSString *)Traineename Rating:(NSString *)Rating; {
const char *dbpath=[databasePath UTF8String];
if(sqlite3_open(dbpath, &database)==SQLITE_OK) {
NSString *insertSQL=[NSString stringWithFormat:#"insert into Feedbackdetails(Traineeid,Trainername,Traineename,Rating) values(\"%d\",\"%#\", \"%#\", \"%#\")",[Traineeid integerValue],Trainername,Traineename,Rating];
const char *insert_stmt=[insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt, -1, &statement, NULL);
if(sqlite3_step(statement)==SQLITE_DONE) {
return YES;
}
else {
return NO;
}
sqlite3_reset(statement);
}
return NO;
}
Ratingviewcontroller.m
-(IBAction)saveData:(id)sender {
BOOL success=NO;
NSString *alertString = #"Data Insertion failed";
if (Traineeid.text.length>0 &&Trainername.text.length>0 &&Traineename.text.length>0 &&Rating.text.length>0 ) {
success=[[DBManager getSharedInstance]saveData:Traineeid.text Trainername:Trainername.text Traineename:Traineename.text Rating:Rating.text];
}
else {
alertString = #"Enter all fields";
}
if (success == NO) {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle: alertString message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
You are not using the documents directory but the documentation directory. Use this NSDocumentsDirectory instead of NSDocumentationDirectory. Or even better, use the caches directory NSCachesDirectory because documents directory sync with iCloud and Apple might not like it since Documents directory should contain only user-downloaded files.

confused in sqlite select statement

I am trying get the data from my database but i am not getting solve out
I try like this
-(void)information
{
//[self createEditableCopyOfDatabaseIfNeeded];
NSString *filePath = [self getWritableDBPath];
sqlite3 *database;
if(sqlite3_open([filePath UTF8String], &database) == SQLITE_OK)
{
NSString *qu = #"Select Name FROM empl where SyncStatus ='1'";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [qu UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
{
char *firstColumn = (char *)sqlite3_column_text(compiledStatement, 0);
if (firstColumn==nil)
{
NSString *name= [[NSString stringWithUTF8String:firstColumn]autorelease];
NSLog(#"%c",name);
}
if(sqlite3_step(compiledStatement) != SQLITE_ROW )
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"User is not valid" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
it get crash And
It show me error that reason: '* +[NSString stringWithUTF8String:]: NULL cString'
* Call stack at first throw:
use like this
if(sqlite3_step(compiledStatement) == SQLITE_ROW )
{
char *firstColumn = (char *)sqlite3_column_text(compiledStatement, 0);
NSString *name= [[NSString alloc]initWithUTF8String:firstColumn];
}
I hope it will help you try this
I think firstColumn is NULL , it make program crash . You try to check data in database is null.
This is actually obvious because you are trying to fetch data which is NULL
Try for this code for checking NULL in your code:
if (sqlite3_column_text(compiledStatement, 0)!= nil)
i.e.
if (sqlite3_column_text(compiledStatement, 0)!= nil)
char *firstColumn = (char *)sqlite3_column_text(compiledStatement, 0);
else
char *firstColumn = #"";
NSString *name= [[NSString stringWithUTF8String:firstColumn]autorelease];
NSLog(#"%c",name);
try this...
Hope it helps....
I think there are 2 issues with this piece of code.
As already pointed out you are checking for equal to nil and not for
different from nil.
To order of the sql functions should be:
sqlite3_open
sqlite3_prepare_v2
sqlite3_step
sqlite3_column_text
You can also read about this order of statements at:
http://www.iosdevelopment.be/sqlite-tutorial/

Making selectedSegmentIndex select nothing after selection

I have a UISegmentControl that select nothing through IB, after the user selects the segment it becomes selected. How do i do it so that it doesnot gets selected?
//Show question method
-(void)question:(NSInteger)i
{
// Path to the plist
NSString *path = [[NSBundle mainBundle] pathForResource:#"Question" ofType:#"plist"];
// Set the plist to an array
NSArray *array = [NSArray arrayWithContentsOfFile:path];
//Check the number of entries in the array
NSInteger numCount = [array count];
if(i <numCount)
{ NSDictionary *dict = [array objectAtIndex:i];//load array index 0 dictionary data
self.title = [NSString stringWithFormat:#"Question %d", i+1];//set the nav bar title
quest.text = [dict valueForKey:#"Question"];//Set the Question to storage
ans.text = [dict valueForKey:#"Answer"];//Set the Answer to storage
NSInteger option = [[dict valueForKey:#"NumberOfOption"] integerValue ];//Check options to determine the question type
//check if the option is is a QRCode or Multiple Choices Question
if (option ==0)
{
QRbutton.alpha = 1; //show the QR Code Button If there is no options
OptionsAnswer.alpha = 0;//Hide Option if there is no options
}
else
{
QRbutton.alpha = 0.0;//Hide QR Code Button if there is options
OptionsAnswer.alpha = 1;//Show Option if there is options
[OptionsAnswer setTitle:[dict valueForKey:#"Option1"] forSegmentAtIndex:0];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option2"] forSegmentAtIndex:1];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option3"] forSegmentAtIndex:2];//Set Option Answer Value
[OptionsAnswer setTitle:[dict valueForKey:#"Option4"] forSegmentAtIndex:3];//Set Option Answer Value
[OptionsAnswer addTarget:self action:#selector(OptionAnswerCheck) forControlEvents:UIControlEventValueChanged];//Call action when options is being selected
}
}
else {
//if question is all answered, it will prompt an alert for end game video.
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Well Done"
message:#"You Have Answered All The Questions, Oh Wait A Minute I Heard A Cracking Sound...." delegate:self
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
}
//Check if the selected Option is correct
-(IBAction)OptionAnswerCheck
{
//define a persistant location to save which question has been answered
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];//question storages
//pass the value from the selected option to a string
//NSString * selectedTitle = ([OptionsAnswer selectedSegmentIndex] >= 0) ? [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]] :
NSString * selectedTitle = [OptionsAnswer titleForSegmentAtIndex:[OptionsAnswer selectedSegmentIndex]];
NSLog(#"Selected Title = %#",selectedTitle);//test
//check if the selected value is equal to the answers
if ([selectedTitle compare:self.ans.text] ==NSOrderedSame)
{
//Popup to say answer Correct
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Correct!"
message:#"Nice Work, Lets Move On To The Next Question" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
//increase the question number
[self question:++currentQuestion];
//save increased question
[userDefaults setInteger:currentQuestion forKey:#"currentQuestion"];
}
else
{
//Popup to say answer Wrong
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:#"Incorrect"
message:#"Close! But That's Not Right, Try Another Answer" delegate:nil
cancelButtonTitle:#"Try Again." otherButtonTitles:nil] autorelease]; [alert show];;
[alert performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:NO];
}
//OptionsAnswer.selectedSegmentIndex = UISegmentedControlNoSegment;
}
Just search for setMomentary: in your developer documentation inside Xcode.
I'm not entirely sure what you're asking here, but I think that you want to set the momentary property toYES.
The property is in the inspector of IB as well. (Can't post a screenshot, I'm on my iPhone).

iphone - SQLite records on table not coming?

I have a table and 3 records.
and I have the code;
-(void) readScoreFromDatabase {
sqlite3 *database;
scores = [[NSMutableArray alloc] init];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStatement = "select name,score from game";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
//if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aName =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *aScore =[NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
DatabaseClass *dbOBJ = [[DatabaseClass alloc] initWithName:aName score:aScore];
[scores addObject:dbOBJ];
[dbOBJ release];
}
}
sqlite3_finalize(compiledStatement);
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"No Connection"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
sqlite3_close(database);
}
and I am using that code to show records;
-(IBAction)refreshClick:(id)sender {
// Navigation logic -- create and push a new view controller
IDRGameAppDelegate *appDelegate = (IDRGameAppDelegate *)[[UIApplication sharedApplication] delegate];
DatabaseClass *dbOBJ = (DatabaseClass *)[appDelegate.scores objectAtIndex:1];
game1NameLabel.text = dbOBJ.name;
score1Label.text = dbOBJ.score;
}
I have 3 records, but I can take only one record. I mean changed that line "DatabaseClass *dbOBJ = (DatabaseClass *)[appDelegate.scores objectAtIndex:1];"
objectAtIndex:1 when I change this value 1 or 2 or 3 etc. the result doesn't change. It is always showing one record from 3 records. I don't understand the reason.
Thank you.
Are you able to see the table rows, when you go to the SQLite manager (from Firefox) and run the below query:
select name,score from game;
If you are able to see 3 records, then:
Go to the iPhone simulator and reset settings
(which will clear all the temp caches, database, and build files).
Go to Xcode and do a Build and GO.
This will get you latest database; put it in the Build folder.
This may not be the answer you want, but you should really consider using Core Data now that it's in iPhone OS 3.0. It handles most of this for you and is very easy to use.
Maybe you forgot to set score to your delegate?
scores = [[NSMutableArray alloc] init];
....
//I don't see this in your code
((IDRGameAppDelegate *)[[UIApplication sharedApplication] delegate]).score = score;

Accessing an SQLite DB for two separate queries on iPhone App Initialization

I was successfully accessing my database to get a list of cities on the App launch. I tried running a second query against it right afterward to get the list of States but all that happens is that my app blows up with no usable error in the console (simply says "Program received signal: EXEC_BAD_ACCESS" and nothing more).
Here is the code, I was hoping someone could potentially explain to me what I'm doing wrong:
-(void) initializeDatabase{
// The database is stored in the application bundle
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"mydatabase.sqlite"];
// Open the database. The database was prepared outside the application.
if (sqlite3_open([path UTF8String], &database) == SQLITE_OK){
[self initializeCities:database];
[self initializeStates:database];
} else {
// Even though the open failed, call close to properly clean up resources.
sqlite3_close(database);
NSAssert1(0, #"Failed to open database with message '%s'.", sqlite3_errmsg(database));
// Additional error handling, as appropriate...
}
}
-(void) initializeCities:(sqlite3 *)db {
NSMutableArray *cityArray = [[NSMutableArray alloc] init];
self.cities = cityArray;
[cityArray release];
// Get the primary key for all cities.
const char *sql = "SELECT id FROM my_table ORDER BY state";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK){
while (sqlite3_step(statement) == SQLITE_ROW){
int primaryKey = sqlite3_column_int(statement, 0);
City *city = [[City alloc] initWithPrimaryKey:primaryKey database:db];
[cities addObject:city];
[city release];
}
}
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
}
-(void) initializeStates:(sqlite3 *)db {
NSMutableArray *statesArray = [[NSMutableArray alloc] init];
self.states = statesArray;
[statesArray release];
// Get the primary key for all cities.
const char *sql = "SELECT DISTINCT state FROM my_table ORDER BY state";
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK){
// We "step" through the results - once for each row
while (sqlite3_step(statement) == SQLITE_ROW){
NSString *state;
state = (NSString *)sqlite3_column_text(statement, 0);
[states addObject:state];
[state release];
}
}
// "Finalize" the statement - releases the resources associated with the statement.
sqlite3_finalize(statement);
}
I can't debug this code as the debugger never hits my breakpoints at all.
If I remove the initializeStates method the app works as expected (albiet without a list of states).
You are releasing "state" without having allocated it. Try something like this:
while (sqlite3_step(statement) == SQLITE_ROW){
NSString *state = [[NSString alloc] initWithCString:(char*)sqlite3_column_text(statement, 0) encoding:NSASCIIStringEncoding];
//state = (NSString *)sqlite3_column_text(statement, 0);
[states addObject:state];
[state release];
}
Update: add cast above to fix compiler warning
Your problem is this:
NSString *state = (NSString *)sqlite3_column_text(statement, 0);
According to the documentation, sqlite3_column_text() returns a char*, not an NSString*.
Edit: You wouldn't have had this problem if you'd have used a wrapper ;)