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();
po jsonDict (NSDictionary *) $1 = 0x07569fb0 { article = Hello; timestamp = 123456789; title = Welcome; }
– emotality Nov 7 '12 at 19:44mysql_*
functions as they are in the deprecation process. Be a better PHP Developer. Also your code has significant security concerns. – Jason McCreary Nov 7 '12 at 19:45