【发布时间】:2010-12-10 18:17:55
【问题描述】:
这让我发疯了。它看起来很简单,我可能遗漏了一些明显的东西——并且强烈怀疑这是因为我缺乏 PHP/mysql 技能,但我无法让它工作。我在其他地方努力寻找(并被盗)了一些来自 StackOverflow 的代码 sn-ps 试图解决这个问题,但我仍然不相信我已经让它工作了。
我正在尝试从 Xcode 将 NSDictionary 对象编码为 JSON(使用 JSON 框架),以便我可以使用 PHP POST 方法将数组动态存储在 mysql 中(理想情况下作为单个扁平对象 - 我知道,我知道)。
代码如下。我可以创建 json 好的。我可以连接好,我可以更改不是数组变量和不需要通过 json 发送的变量,我可以做任何事情。我似乎无法传递该 json 并将其存储在 mysql 中。
是的-我是菜鸟。
谢谢...
我已经走到这一步了:
在 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];
在 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();
?>
【问题讨论】:
标签: php iphone mysql xcode json