checking login and password in iphone - iphone

Hi i am trying to create a login and password for my app by using SQLite,, every thing is fine but the once the login button is pressed it is not entering in to home page!!!!
please find my code below:
-(void)checkindatabase{
NSArray *dirPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir =[dirPath objectAtIndex:0];
NSString *databasePath =[[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:#"login.db"]];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
NSString *sql = [[NSString alloc] initWithFormat:#"select * from UserInformation where Username='%#' and Password='%#'",loginName.text,password.text]; //[sql UTF8String];
//NSLog(#"'%s'",[sql UTF8String]);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{ if(sqlite3_step(statement) == SQLITE_ROW)
{
//user name is correct
//if u want to print in log use below code
homepage *hvc = [[homepage alloc]initWithNibName: nil bundle: nil];
hvc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:hvc animated: YES];
}
else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Login Failed!!!"
message:#"Check your PId and Password" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}}
sqlite3_finalize(statement);
}
sqlite3_close(database);
}
-(IBAction)homePage: (id)sender
{
[self checkindatabase];
}

Please find the code, as you asked.
-(BOOL)checkindatabase
{
NSArray *dirPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir =[dirPath objectAtIndex:0];
NSString *databasePath =[[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:#"login.db"]];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
NSString *sql = [[NSString alloc] initWithFormat:#"select * from UserInformation where Username='%#' and Password='%#'",loginName.text,password.text]; //[sql UTF8String];
//NSLog(#"'%s'",[sql UTF8String]);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{ if(sqlite3_step(statement) == SQLITE_ROW)
{
//user name is correct
//if u want to print in log use below code
return YES;
}
}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return NO;
}
-(IBAction)homePage: (id)sender
{
if( [self checkindatabase] )
{
homepage *hvc = [[homepage alloc]initWithNibName: nil bundle: nil];
hvc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:hvc animated: YES];
[hvc release];
}
else
{
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Login Failed!!!"
message:#"Check your PId and Password" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
}

As suggested by Aadhira...
Make checkindatabase with return type BOOL and return TRUE if Login successful and FALSE otherwise.
Then on the basis of BOOL value navigate to Home Page.
you cannot let other function to navigate the view, while performing IBAction method.
EDIT :
I am not looking to your database code.. i have simply shown you way how to use the BOOL return values.... Also mention errors if any you faced.
-(BOOL)checkindatabase{
NSArray *dirPath =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir =[dirPath objectAtIndex:0];
NSString *databasePath =[[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:#"login.db"]];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"open");
NSString *sql = [[NSString alloc] initWithFormat:#"select * from UserInformation where Username='%#' and Password='%#'",loginName.text,password.text]; //[sql UTF8String];
//NSLog(#"'%s'",[sql UTF8String]);
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)
{ if(sqlite3_step(statement) == SQLITE_ROW)
{
//user name is correct
//if u want to print in log use below code
flag = YES;
}
else {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"Login Failed!!!"
message:#"Check your PId and Password" delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
flag = NO;
}}
sqlite3_finalize(statement);
}
sqlite3_close(database);
return flag;
}
-(IBAction)homePage: (id)sender
{
BOOL newFlag = [self checkindatabase];
if(newFlag)
{
homepage *hvc = [[homepage alloc]initWithNibName: nil bundle: nil]
hvc.modalTransitionStyle=UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:hvc animated: YES];
}
}

Related

Once i get the alert i am not able to add the persons into my database

(void)addPersonButton:(id)sender {
char *error;
if (sqlite3_open([dbPathString UTF8String], &personDB) == SQLITE_OK) {
if ([nameField.text length] > 0 && [ageField.text length] > 0 ){
//{NSLog(#"mobile num %#", mobileNumField.text);
//NSCharacterSet *decimalSet = [NSCharacterSet decimalDigitCharacterSet];
//if ([mobileNumField.text rangeOfCharacterFromSet:decimalSet].location == NSNotFound) {
NSString *phoneNum = #"^(\\+91||0)?\\d{10}";
NSPredicate *test = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", phoneNum];
BOOL matches = [test evaluateWithObject:[mobileNumField text]];
BOOL valid;
if (matches) {
sqlite3_stmt *statement;
NSString *querySQL = [NSString stringWithFormat:#"SELECT * FROM PERSONS"];
const char *query_sql = [querySQL UTF8String];
if (sqlite3_prepare(personDB, query_sql, -1, &statement, NULL) == SQLITE_OK) {
while (sqlite3_step(statement) == SQLITE_ROW) {
NSString *mobilenum = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 3)];
NSLog(#"in DB: %# and in TF:%#", mobilenum, mobileNumField.text);
NSInteger len = [mobileNumField.text length];
NSLog(#"len %d",len);
// if (len > 10) {
NSInteger len1 = len - 10;
NSString *string = [mobileNumField.text substringWithRange:NSMakeRange(len1, 10)];
NSRange find = [mobilenum rangeOfString:string];
NSLog(#"find length %d",find.length);
//}
if (find.length) {
valid = false;
break;
}//else {NSLog(#"am in else");
valid = true;
//break;
//}
}NSLog(#"am out of while");
if (valid) {
NSLog(#"am inside valid if");
NSLog(#"%#", mobileNumField.text);
NSString *insertStmt = [NSString stringWithFormat:#"INSERT INTO PERSONS(NAME,AGE,MOBNUM) values ('%s','%d','%s')" ,[self.nameField.text UTF8String], [self.ageField.text intValue],[self.mobileNumField.text UTF8String]];
const char *insert_stmt = [insertStmt UTF8String];
NSLog(#"insertStmt=%# and insert_stmt = %s",insertStmt,insert_stmt);
int flag1 = (sqlite3_prepare(personDB, query_sql, -1, &statement, NULL) == SQLITE_OK);
int flag = (sqlite3_exec(personDB, insert_stmt, NULL, NULL, &error) == SQLITE_OK);
NSLog(#"flag1 = %d and flag = %d", flag1, flag);
if (flag) {
NSLog(#"Person Added");
Person *person = [[Person alloc] init];
[person setName:self.nameField.text];
[person setAge:[self.ageField.text intValue]];
[person setNumber:self.mobileNumField.text];
[arrayOfPersons addObject:person];
nameField.text = #"";
nameField.placeholder = #"Name ";
ageField.text = #"";
ageField.placeholder = #"Age";
mobileNumField.text = #"";
}else NSLog(#"person not added");
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Already registered with this mobile num" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
}
}
else {
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Sorry, It's not valid mobile number. Please enter again" delegate:self cancelButtonTitle:#"ok" otherButtonTitles: nil];
[alert1 show];
}
}
else {
UIAlertView *alert2 = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Name and Age fields are should not be empty" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert2 show];
}
sqlite3_close(personDB);
}
}
In the above code am taking mobile number as a primary key, so whenever I registered with same mobile number then it shows the "alert" after getting the alert am giving another mobile number that is not registered before, at that time my SQL query (sqlite3_exec(personDB, insert_stmt, NULL, NULL, &error) == SQLITE_OK) is does not execute. I didn't understand why my SQL query is not executed. Please give me solution.
Did you enable ARC? if no did you release your Alert?
NSApplicationSupportDirectory is the one that works best for you, place your DB in NSApplicationSupportDirectory and then have access to the data from there and you can do insert and other operations. :)

How to compare my email text field value to database value in iphone

I have a problem in comparing my textfield email value to the value in sqlite database. If both the values are same then it shows alertbox that "email already exist in database". I have created a function for this purpose named findcontact, I am calling the function from button click. Button click method is working because when I click the button then buttonclick method generate the log which I have written in findContact method.
But problem for me is that how to compare both the email and show alert box if both email matches
- (void) findContact:(NSString *) email{
const char *dbpath = [path UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK){
NSString *querySQL = [NSString stringWithFormat: #"SELECT email FROM CONTACT WHERE email=\"%#\"",email];
NSLog(#" email = %#", querySQL);
const char *query_stmt = [querySQL UTF8String];
NSLog(#" char email = %s", query_stmt);
if (sqlite3_prepare_v2(database, query_stmt, -1, &init_statement, NULL) == SQLITE_OK){
if (sqlite3_step(init_statement) == SQLITE_ROW){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"email already exist in database" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK ", nil];
[alert show];
[alert release];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"email not exist" delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK ", nil];
[alert show];
[alert release];
}
sqlite3_finalize(init_statement);
}
sqlite3_close(database);
}
}
Do comparison like this in your code
while(sqlite3_step(compiledStatement)==SQLITE_ROW)
{
NSString *emaiID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement,0)];
if ([emaiID isEqualToString:yourTextField.text])
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"email already exist in database"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"OK ", nil];
[alert show];
}
else{
//Your task
}
}
Check this
NSString *querySQL = [NSString stringWithFormat: #"SELECT email FROM CONTACT WHERE email='%#'",email];
if(sqlite3_prepare_v2(sharedDataBase, [querySQL UTF8String], -1, &statment, nil) == SQLITE_OK)
{
if(sqlite3_step(statment)==SQLITE_ROW){
char *email=(char *)sqlite3_column_text(statment, 0);
NSString *emailStr =[NSString stringWithUTF8String:email];
// email exist
}
else{
// email not exist
}
sqlite3_finalize(statment);
}
else
sqlite3_close(sharedDataBase);

the insert method not working

I am working on sqlite database , trying to insert into database but it is not working proper. I searched some post and also write reset and finalize statement.
(void)addLimittypeForeign
{
// Create insert statement for the person
if(sqlite3_open([dbPath UTF8String],&database) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:
#"insert into Limittabel (limitid,limitAmt,Profileid) Values (?,?,?)"];
char *errmsg=nil;
if(sqlite3_exec(database, [querySQL UTF8String], NULL, NULL, &errmsg)
!= SQLITE_OK )
{
NSLog(#"YES THE DATA HAS BEEN WRITTEN SUCCESSFULLY");
}
}
sqlite3_close(database);
}
Please Help Me.Thanks
use this code for insertion is database .... change code according to your requirement...working fine for me...
-(void) insertDataIntoDatabase
{
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:#"dataBaseName.sqlite"];
NSLog(#"%#",sender);
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSLog(#"%#",[quoteDic objectForKey:#"bookmark"]);
NSLog(#"%d",[[quoteDic objectForKey:#"quoteId"] intValue]);
NSString *sqlStatement=[NSString stringWithFormat:#"insert into tableName (frndName,frndDescription,frndAddress,frndMobile,frndEmail,frndCollege,frndCompany) Values('%#','%#','%#','%#','%#','%#','%#')",[frndName text],[frndDescription text],[frndAddress text],[frndMobile text],[frndEmail text],[frndCollege text],[frndCompany text]];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [sqlStatement UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
{
}
if(sqlite3_step(compiledStatement) != SQLITE_DONE)
{
//sqlite3_close(database);
NSAssert1(0, #"Error while Updating data. '%s'", sqlite3_errmsg(database));
sqlite3_finalize(compiledStatement);
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Update!!"
message:#"Your record Updated"
delegate:nil
cancelButtonTitle:#"Thankyou"
otherButtonTitles:nil];
[alert show];
[alert release];
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}

updating table row using SQLite3

Am using SQLite3. and am updating row which is already present by using following code
- (BOOL)updateTableData :(NSString *) num
{
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
dbPath = [self getDBPath:#"studentslist.sqlite"];
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
sqlite3_stmt *updateStmt;
const char *sql = "update studentInfo set sAge=?, sAddrs1=?, sAddrs2=?, sMobile =?, sClass =? where sRollNumber=?;";
if(sqlite3_prepare_v2(database, sql, -1, &updateStmt, NULL) != SQLITE_OK)
{
NSLog(#"updateTableData: Error while creating delete statement. '%s'", sqlite3_errmsg(database));
return;
}
NSLog(#"appDelegate.updateArray %#",appDelegate.updateArray);
sqlite3_bind_int(updateStmt, 1,[[appDelegate.updateArray objectAtIndex:0] intValue]);
sqlite3_bind_text(updateStmt, 2,[[appDelegate.updateArray objectAtIndex:1] UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 3,[[appDelegate.updateArray objectAtIndex:2] UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 4,[[appDelegate.updateArray objectAtIndex:3] UTF8String], -1,SQLITE_TRANSIENT);
sqlite3_bind_text(updateStmt, 5,[[appDelegate.updateArray objectAtIndex:4] UTF8String], -1,SQLITE_TRANSIENT);
if (SQLITE_DONE != sqlite3_step(updateStmt))
{
NSLog(#"updateTableData: Error while updating. '%s'", sqlite3_errmsg(database));
sqlite3_finalize(updateStmt);
sqlite3_reset(updateStmt);
sqlite3_close(database);
return NO;
}
else
{
NSLog(#"updateTableData: Updated");
sqlite3_finalize(updateStmt);
sqlite3_close(database);
return YES;
}
}
else
{
NSLog(#"updateTableData :Database Not Opened");
sqlite3_close(database);
return NO;
}
in main class am calling this method as follows
-(IBAction)updateButtonAction:(id)sender
{
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
db = [[Database alloc]init];
if ([ageTxtFld.text length]>0 && [address1TxtFld.text length]>0 && [address2TxtFld.text length]>0 && [mobileTxtFld.text length]>0 && [classTxtFld.text length]>0)
{
[appDelegate.updateArray addObject:ageTxtFld.text];
[appDelegate.updateArray addObject:address1TxtFld.text];
[appDelegate.updateArray addObject:address2TxtFld.text];
[appDelegate.updateArray addObject:mobileTxtFld.text];
[appDelegate.updateArray addObject:classTxtFld.text];
NSLog(#"appDelegate.updateArray %#",appDelegate.updateArray);
NSString *num = rollNumberTxtFld.text;
BOOL is = [db updateTableData:num];
if (is == YES)
{
updateAlert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Updated" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[updateAlert show];
}
else
{
updateAlert = [[UIAlertView alloc] initWithTitle:#"Fail" message:#"Not Updated" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[updateAlert show];
}
}
else
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Enter all values" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlert show];
}
}
But it always printing NSLog(#"updateTableData: Updated"); but not updating
Any one can suggest me or help with code.
Thanks in Advance
- (void)createEditableCopyOfDatabaseIfNeeded {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"studentslist.sqlite"];
dbPath =writableDBPath;
[databasePath retain];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"studentslist.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
writableDBPath = nil;
documentsDirectory = nil;
paths = nil;
}
Write this method in your code and call it. surely this was a problem in your code.

how to updtae Sqlite last insert row id in iphone?

I am making an application where i want to use update query?
In my application i have two stages to complete the registration process
in page1 i have registration form and one submit button?
on click of submit button all the details should get insert into my sqlite table.
in page2 i have confirmation page and one edit and continue button?
all the value saved in a table should be view by the user on this page and if he want's to make any change he should be able to do that. once user had edited some value and he press continue button all the value insert should get updated?
but i have try doing this but i am not able to update the last enter value?
following is my code page1 insert code:
-(void)submit
{
if( ([UserName.text isEqualToString:#""]) || ([Password.text isEqualToString:#""]) ||
([ConfirmPassword.text isEqualToString:#""]) || ([Name.text isEqualToString:#""]) ||
([Email.text isEqualToString:#""]) || ([ContactNO.text isEqualToString:#""]) ||
([MobileNo.text isEqualToString:#""]) || ([Address.text isEqualToString:#""]) )
{
UIAlertView *ErrorAlert = [[UIAlertView alloc] initWithTitle:#"Error!!"
message:#"Please fill in the details." delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[ErrorAlert show];
[ErrorAlert release];
}
else
{
Confirmation_form *conForm = [[Confirmation_form alloc] initWithNibName:#"Confirmation_form" bundle:nil];
conForm.data = UserName.text;
conForm.data1 = Password.text;
conForm.data2 = ConfirmPassword.text;
conForm.data3 = Name.text;
conForm.data4 = Email.text;
conForm.data5 = ContactNO.text;
conForm.data6 = MobileNo.text;
conForm.data7 = Address.text;
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &test1DB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"INSERT INTO test(UserName, Password, ConfirmPassword, Name, Email, ContactNO, MobileNo, Address) VALUES (\"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\")",UserName.text, Password.text, ConfirmPassword.text, Name.text, Email.text, ContactNO.text, MobileNo.text, Address.text];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(test1DB, insert_stmt, -1, &statement, NULL);
if(sqlite3_step(statement) == SQLITE_DONE)
{
//status.text = #"Contact added";
UserName.text = #"";
Password.text = #"";
ConfirmPassword.text = #"";
Name.text = #"";
Email.text = #"";
ContactNO.text = #"";
MobileNo.text = #"";
Address.text = #"";
sqlite3_last_insert_rowid;
rowID = sqlite3_last_insert_rowid(test1DB);
NSLog(#"last inserted rowId = %d",rowID);
sqlite3_reset(statement);
sqlite3_finalize(statement);
sqlite3_close(test1DB);
[self.navigationController pushViewController:conForm animated:YES];
}
}
}
}
from the above code i am able to get the row id but i am not able to use that rowid in update query
following is my code page2 Update code:
-(IBAction)Update;
{
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &test1DB) == SQLITE_OK)
{
NSString *insertSQL = [NSString stringWithFormat:#"UPDATE test SET UserName='%#',Password='%#',ConfirmPassword='%#',Name='%#',Email='%#',ContactNO='%#',MobileNO='%#',Address='%#'WHERE ID='%#'",UserName.text,Password.text,ConfirmPassword.text, Name.text, Email.text, ContactNO.text, MobileNo.text, Address.text, sqlite3_last_insert_rowid(test1DB)];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(test1DB, insert_stmt, -1, &statement, NULL);
if(sqlite3_step(statement) == SQLITE_DONE)
{
sqlite3_step(statement);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record added" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
sqlite3_finalize(statement);
sqlite3_close(test1DB);
}
else {
sqlite3_step(statement);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Record notadded" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert = nil;
}
}
Simple Way -> create "someconstant.h" file declare your _rowID variable there.
Import file in your class,assign your value in first class and used it in second class.