I have a method that should post some data to a PHP file:
-(void)submitForm {
NSLog(@"name=%@", formName.text); // returns correct value
NSString *post = [NSString stringWithFormat:@"name=%@&", formName.text];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://path/to/file"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"%@",responseString);
}
Note: I’m not actually using @"http://path/to/file". I’ve omitted the URL for privacy.
I believe it’s connecting to the PHP script correctly, since I’m receiving the response I expect. The problem is that if I echo out $name, I get an empty string. Here’s the script:
<?php
include("config.php"); // Handles DB connection
$name = mysql_escape_string($_POST["name"]);
mysql_query("insert into objects(name) values('$name')") or die(mysql_error());
echo $name; // returns empty string
All I expect is some sort of syntax/logic error in the Obj-C code, but I can’t spot it.
I’ve got a feeling that your request is missing some mandatory data, a boundary and content-type, which might lead to your POST request being half complete.
I’ll show you what I’ve done for uploading an HTML file to a webserver and then explain underneath.
Objective-C
PHP
You’ll need to change a few things around to fit your SQL insert and strip out my file stuff, but it’s a start.
This is the part I think you’re missing.
The boundary can be a series of random numbers, but it has to exist.
Also, watch out when constructing the body of the request, especially the slashes. Make sure you escape any ” “.