This is driving me nuts. It seems so simple, and I am likely missing something obvious - and strongly suspect it's because my PHP/mysql skills are lacking, but I can't get it to work. I have looked hard elsewhere (and stolen) a number of code snippets from StackOverflow trying to solve the issue, but I'm still not convinced I've got it working.
From Xcode I'm trying to encode an NSDictionary object into JSON (using JSON framework) so that I can dynamically store the array in mysql (ideally as a single flattened object - I know, I know) using PHP POST method.
Code is below. I can create the json ok. I can connect ok, I can change variables that arent array variables & that do not need to be send via json, I can do just about anything. I can't seem to pass that json and store it in mysql.
Yes- im a noob.
Thx...
I've got this far:
in xcode
NSDictionary *loginDict = [NSDictionary dictionaryWithObjectsAndKeys:
@"aname", @"username",
@"hello", @"password",
nil];
NSString *jsonString = [loginDict JSONRepresentation];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *post = [NSString stringWithFormat:@"json=%@", jsonString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
[request setURL:[NSURL URLWithString:@"http://domain.com/post_dict.php"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
at post_dict.php
<?php
$rawJsonData = $_POST['json'];
$decodedData = json_decode($rawJsonData); //do i even need to decode if i want to store a flattened json object in mysql?
//Connect To Database
$hostname='**BLACKEDOUT**.com';
$username='**BLACKEDOUT**';
$password='**BLACKEDOUT**';
$dbname='**BLACKEDOUT**';
$usertable='users';
//I want to update the Records field with the array
$recordsfield = 'Records';
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$query = "UPDATE $usertable SET $recordsfield = '$decodedData' ";//do i encode? serialize? dunno
$result = mysql_query($query);
if(!$result)
{
mysql_close();
echo mysql_error();
return;
}
mysql_close();
?>