0

我在实际使用 POST 来保存/更改数据库上的信息时遇到了麻烦。有人可以帮我吗?

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];

上面的代码来自应用程序,我的服务器端代码如下所示:另外请不要认为此代码位于 php 文件中

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"]));
}
4

2 回答 2

0

您是否在 PHP 代码中解码了 JSON 对象?

或者

尝试如下设置

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

而且我不确定您是否需要关注

[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

希望这可以帮助。

于 2013-03-22T13:00:25.460 回答
0

也许不是最理想的方式,但我可以提出一个可行的方式;

在 iOS 端;

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

在php方面;

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

    echo $json_user["name"];
?>
于 2013-03-22T13:09:16.577 回答