how to updtae Sqlite last insert row id in iphone? - 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.

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);

sqlite3_prepare_v2 returning 21 & "could not prepare statemnt: out of memory"

I am getting these errors, everything is in here. All I am doing is creating a .db file with a path specified by Xcode, and then creating a table with the shown values as columns. I then try to go ahead and populate the table but receive the errors above in the title (seems as though these are what are causing my headaches). If someone could shed some light on this, it would be greatly appreciated.
#import "Email.h"
#implementation Email
#synthesize to, cc, bcc, fromName, fromEmail, headers, datetime, subject, body, folder, state, attachments;
-(void)StoreEmail:(Email *)email{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the database file
databasePath = [[NSString alloc]
initWithString: [docsDir stringByAppendingPathComponent:
#"contacts2.db"]];
NSFileManager *filemgr = [NSFileManager defaultManager];
if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB2) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS2 (ID INTEGER PRIMARY KEY AUTOINCREMENT, FROM TEXT, NAME TEXT, SUBJECT TEXT, BODY TEXT, ATTACHMENTS TEXT, HEADERS TEXT, DATETIME TEXT, FOLDER TEXT, STATE TEXT)";
if (sqlite3_exec(contactDB2, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"path" message:#"failed to create table" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
sqlite3_close(contactDB2);
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"path" message:#"failed to open/create database" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"path" message:databasePath delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB2) == SQLITE_OK)
{
NSLog(#"This is what open returns %d", sqlite3_open(dbpath, &contactDB2));
//NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO CONTACTS2 (from, name, subject, body, attachments, headers, datetime, folder, state) VALUES (\"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\", \"%#\")", email.fromEmail, email.fromName, email.subject, email.body, email.attachments, email.headers, email.datetime, email.folder, email.state];
NSString *insertSQL = [NSString stringWithFormat: #"INSERT INTO CONTACTS2 (from, name) VALUES (\"%#\", \"%#\")", email.fromEmail, email.fromName];
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(contactDB2, insert_stmt, -1, &statement, NULL);
NSLog(#"could not prepare statemnt: %s\n", sqlite3_errmsg(database));
//NSLog(#"%d", sqlite3_prepare_v2(contactDB2, insert_stmt, -1, &statement, NULL));
if (sqlite3_step(statement)== SQLITE_DONE)
{
NSLog(#"2");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"path" message:#"email added" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else
{
NSLog(#"%d", sqlite3_step(statement));
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"path" message:#"failed to add email" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
sqlite3_finalize(statement);
sqlite3_close(contactDB2);
}
}

checking login and password in 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];
}
}

invalide username or password when validate it sqlite iphone

when Click on update button then data does not updated i want to just updated my password
first match old password
if old password match with database then validate new password and conform password using isEquelToString then click on update button and oldpassword must be updated with newPassword
I think user name and password match for single user only there for if it match then it will return one row using following code. Check the following code i think this will work for you.
-(void)checkingDatabase{
databaseName = #"trylogin.sqlite";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [[documentsDir stringByAppendingPathComponent:databaseName]retain];
NSLog(#"databse path %#",databasePath);
database = nil;
int myInt = 0;
if(sqlite3_open([databasePath UTF8String], &database) ==SQLITE_OK){
NSString *sql = [[NSString alloc] initWithFormat:#"select COUNT(*) from loginTry where userName='%#' and password='%#'",txtusername.text,txtPassword.text];
const char *sqlStatement = [tempSQL cStringUsingEncoding:NSUTF8StringEncoding];
[tempSQL release];
sqlite3_stmt *compiledStatement;
sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL);
if(sqlite3_step(compiledStatement) == SQLITE_ROW) {
myInt = (int)sqlite3_column_int(compiledStatement, 0);
}
sqlite3_finalize(compiledStatement);
sqlite3_close(database);
}
if(myInt ! = 0){
AnimalViewController *FBController = [[AnimalViewController alloc] initWithNibName:#"AnimalViewController" bundle:nil];
[self.view addSubview:FBController.view];
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Wrong username or password" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}
}
As above same but some change at condition checking as follows..
if(myInt ! = 0) {
if([newpassword.text isEqualToString: confirmPassword.text]) {
//Write code for update query.
}
else {
//print message new password and confirm password does not match.
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"UIAlertView" message:#"Wrong username or password" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert show];
[alert release];
}