我觉得这不应该是这么复杂,但在这里我花了最后两天试图让这个工作。我试图将iOS应用程序中的两个变量发送到服务器上的php脚本。数据库添加一个条目,但2个信息字段为空。我很满意Objective C但不熟悉PHP。
PHP代码
<?php
$name = $_POST['name'];
$comment = $_POST['comment'];
mysql_connect("Server","Username","Password");
mysql_select_db("comments");
mysql_query("INSERT INTO comments (id, name, comment) VALUES ('','$name','$comment')");
?>
目标C代码
NSString *name = @"Name1";
NSString *comment = @"Comment1";
NSString *myRequestString = [NSString stringWithFormat:@"&name=%@&comment=%@",name,comment];
NSData *myRequestData =[myRequestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[myRequestData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://www.notguiltyapp.com/harris.php"]];
[request setHTTPMethod: @"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(@"Connection Successful");
}
else
{
NSLog(@"Connection could not be made");
}
答案 0 :(得分:0)
更新:我在更长时间后修复了问题。我拿出了
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
并将其替换为
NSData *returnData=[NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];