Like the title says..
My NSDictionary initWithObjectsAndKeys for JSON, with the POST method, to do MySQL query via PHP code, by using the json_encoding and json_decoding creates empty data in my SQL database, just the ID int is auto increasing every time I post!
My Xcode code:
-(IBAction)setJsonFromData:(id)sender
{
NSDictionary *jsonDict = [[NSDictionary alloc] initWithObjectsAndKeys: @"Welcome", @"title", @"Hello", @"article", @"123456789", @"timestamp", nil];
if([NSJSONSerialization isValidJSONObject:jsonDict])
{
NSError *error = nil;
NSData *result = [NSJSONSerialization dataWithJSONObject:jsonDict options:NSJSONWritingPrettyPrinted error:&error];
if (error == nil && result != nil) {
[self postJSONtoURL:result];
}
}
}
-(id)postJSONtoURL:(NSData *)requestJSONdata
{
NSURL *url = [NSURL URLWithString:@"http://test.com/json.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestJSONdata length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: requestJSONdata];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"RESULT: %@", requestJSONdata);
if (error == nil)
return result;
return nil;
}
My PHP code:
if (isset($_REQUEST))
{
$json = $_REQUEST;
$data = json_decode($json);
$title = $_REQUEST['title'];
$article = $_REQUEST['article'];
$timestamp = $_REQUEST['timestamp'];
mysql_query("INSERT INTO news (title, article, timestamp) VALUES ('$title->title','$article->article','$timestamp->timestamp')");
}
mysql_close();
You’re receiving the json payload in the http body since you do a POST request.
So, you’ll need to decode that:
After that you should be able to access data like:
PHP does not automatically decode incoming json data.
see the docs regarding that
php://inputthing.