insert data to mysql fields empty - mysql

Hi im trying to insert data to a mysql database. I get new content every time i click on save but the columns in the database don't get the text (From the textview and textfields).
-(IBAction)save:(id)sender{
NSString *rawStr = [NSString stringWithFormat:#"location=%#",address.text,#"&long=%#",longitude.text,#"&lat=%#",lat.text,#"&texten=%#",texten.text];
NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:#"http://url.info/projct/phpFile.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseData: %#", responseData);
[self dismissViewControllerAnimated:YES completion:nil];
}
It works when i insert data to database by a webbrowser.

It does not appear that you are setting the request header to indicate that this is form-encoded data. Without this, PHP will not populate $_POST superglobal automatically (also POSTed data will not be reflected in URL). You might want to check php://input to see if you are actually getting the data:
You can do that like this:
$query_string = file_get_contents('php://input');
var_dump($query_string);

Related

NSURLSession POST request return HTML webpage code

I am trying to submit user input to a webpage and then retrieve returned data. This webpage takes a person's name and returns his/her information from a database. I tried to make a POST request when user clicks a button then send user's input to that webpage. But when I print out returned data, it's just the html source code of that webpage, only without javaScript. How can I change/add the below function to get the person's information page? I've spent lots of time but still can't figure it out. Please help me! Thank you!
-(void) sendHTTPPost{
NSString* input = nameTextField.text;
//1
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://find.pitt.edu"]];
[req setHTTPMethod:#"POST"];
//2
NSData* postData = [input dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
//3
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[req setValue:postLength forHTTPHeaderField:#"Content-Length"];
[req setValue:#"text/html" forHTTPHeaderField:#"Content-type"];
[req setHTTPBody:postData];
//4
NSURLSession *session = [NSURLSession sharedSession];
//5
NSURLSessionDataTask *task = [session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// Do something with response data here - convert to JSON, check if error exists, etc....
if(error != nil){
NSLog(#"error: %#", error);
}
else{
NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
NSLog(#"response = %#", response);
}
}];
[task resume];
}
It is unlikely that the POST body is supposed to contain only the value. Chances are, it should contain
key=value&key2=value2&key3=value3...
where key is the name of the input, and value is the value of that input, in a URL-encoded format. (See "Encoding URL Data" in URL Session Programming Guide for details on how to URL-encode the values.)

How to download html file from server (not local) in NSString

I have a html file on some server. The html file only contains text no photo's or anything else.
What I want to do is download the html file and put the text into a NSString.
Is this possible?
I found some code a few minutes ago:
NSURL *url = [NSURL URLWithString:#"http://www.example.com/file.html"];
NSString *text = [[NSString alloc] initWithContentsOfURL: url
encoding: NSUTF8StringEncoding
error: nil];
But did not work
Try this :
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval: 20];
NSError *requestError;
NSHTTPURLResponse *response = nil;
// Send request synchronously.
NSData *responseData = [NSURLConnection sendSynchronousRequest: request
returningResponse: &response
error: &requestError];
// Get the json string reponse.
NSString *stringResponse = [[NSString alloc]initWithData: responseData
encoding:NSUTF8StringEncoding];

How to POST JSON data object to server in iOS7

Hi in my application i have stored data in my local database sqlite3. Now i have to upload the data form local database sqlite3 to online server. For retrieving the data i have used the dataDictionary to get all the data form the sqlite3 database. And i have converted the data in json format now the problem is how to pass this json data into my online server.
NSMutableArray *array = [[NSMutableArray alloc] init];
[self openDB];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM reg"];
const char *query_stmt = [sql UTF8String];
sqlite3_stmt *statement;
if (sqlite3_prepare_v2(db, query_stmt, -1, &statement, nil)==SQLITE_OK) {
while (sqlite3_step(statement)==SQLITE_ROW) {
NSMutableDictionary *_dataDictionary=[[NSMutableDictionary alloc] init];
NSString *date = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
field1Str= date;
NSString *customer = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 1)];
field2Str = customer;
NSString *code1 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 2)];
field3Str = code1;
NSString *code2 = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement,3)];
field4Str = code2;
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field1Str] forKey:#"Kname"];
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field2Str] forKey:#"kphone"];
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field3Str] forKey:#"karea"];
[_dataDictionary setObject:[NSString stringWithFormat:#"%#",field4Str] forKey:#"kcity"];
[array addObject:_dataDictionary];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:array options:kNilOptions error:nil];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *someURLSetBefore =[NSURL URLWithString:#"my url for inserting the data into my online server"];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
// print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
}
I have used this above code to pass my sqlite3 database data to my server. I have print the jsondata in log its coming as a json format data only. Please tell me how to push this data to my online server where I'm missing in the code i have stuck here for very long time its eating my head its not working please help me out.
Thanks.
I suggest that you use some proper framework for HTTP communication. Using Apple's low-level API can be quite tricky.
This is a great framework: https://github.com/AFNetworking/AFNetworking

Show JSON content depending on user id iOS

I want to show the content depending on user id.
The user log-in to the App, after the successful login, he will see the content depending on his id that is retrieved from the JSON file which is connected the the external mysql database.
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *jsonURL = [NSURL URLWithString:#"http://api.example.com/page.php?user_id=1"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
self.something = [dataDictionary objectForKey:#"something"];
}
My problem is :
How to make " 1 " in ( user_id=1 ) dynamic, in a way, it will be changed automatically when the user log-in to his account.
Prepare URL dynamically
NSString *userID = #"23";//Get your userID after login
NSURL *jsonURL = [NSURL URLWithString:[NSString stringWithFormat:#"http://api.example.com/page.php?user_id=%#",userID];
you can use StringWithFormat Method of NSString Class, This methods helps you in creating dynamic NSString Objects,
- (void)viewDidLoad
{
[super viewDidLoad];
NSString userId = #"your user id here";
NSURL *jsonURL = [NSURL URLWithString:[NSString StringWithFormat:#"http://api.example.com/page.php?user_id=%#",userId]];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
self.something = [dataDictionary objectForKey:#"something"];
}

Using Cypher (Neo4j) within a REST API request (Objective C)

I am trying to query my Neo4j database, using the REST API.
I have this working so far without using the Cypher query language to retrieve data,
however, now I need to get nodes which are sorted by 'newest' i.e. unix timestamp DESC.
I have tried to add the query within the HTTP body of the NSMutableURLRequest but I am just getting the HTTP error 405.
Here is my code:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#node/%i", EventsManagerDataURL, creatorID]];
NSLog(#"Connecting to URL: %#", url);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSString *jsonMap = #"{'query' : 'start x = node(4,6,7) return x order by x.datestart,'params' : {}}";
NSData *jsonData = [jsonMap dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", jsonData.length] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data){
NSLog(#"%s. Data: %#", _cmd, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
NSLog(#"Error: %#", error.localizedDescription);
}
}];
You're missing a single quote here:
NSString *jsonMap = #"{'query' : 'start x = node(4,6,7) return x order by x.datestart***'***,'params' : {}}";
And actually, it needs to have double quotes:
NSString *jsonMap = #"{\"query\" : \"start x = node(4,6,7) return x order by x.datestart\", \"params\" : {}}";
Test with cURL:
curl -H Accept:application/json -H Content-Type:application/json -X POST -d '{"query" : "start x = node(4,6,7) return x order by x.datestart", "params" : {}}' localhost:7474/db/data/cypher