Using POST in Goal c

advertisements

I'm having trouble in actually using POST to save/change information on my database. Could someone please help me?

NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:un, @"username", n, @"name", pn, @"phonenumber",em, @"email", nil];

NSError *error;

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[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];

The code above is from the application my server side codes looks like : Also please not that this code is in a php file

if(!isset($_GET["username"]))
{
    // adding new record
    $q = sprintf("insert into users (username, name, phoneNumber, email) values ('%s','%s', '%s', '%s')",
        mysql_real_escape_string($_GET["username"]),
        mysql_real_escape_string($_GET["name"]),
        mysql_real_escape_string($_GET["phone"]),
        mysql_real_escape_string($_GET["email"]));
}
else
{
    // update the  record
    $q = sprintf("update users set name = '%s', phoneNumber = '%s', email = '%s' where username = '%s'",
        mysql_real_escape_string($_GET["name"]),
        mysql_real_escape_string($_GET["phoneNumber"]),
        mysql_real_escape_string($_GET["email"]),
        mysql_real_escape_string($_GET["username"]));
}


Maybe not the most ideal way but I can present a working one;

On iOS side;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:user
                                                       options:kNilOptions
                                                         error:&error];
    if (!jsonData) {
        NSLog(@"Error:%@",error);
    }
    else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }

    NSString * params = [[NSString alloc] initWithFormat:@"user=%@",jsonString];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:kLinkUpdateFacebook]];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]]; // and send the request

On php side;

<?
    $json_user = json_decode($_POST["user"],true);

    echo $json_user["name"];
?>