在我的应用程序中,用户可以发布内容,其他人可以对其发表评论。无论如何,要查看帖子,您会在表格 View 上看到它的标题,然后推送到详细信息 View 。该segue带有帖子ID。要显示评论,我必须将帖子 ID 发送到一个 php 文件。然后我根据该帖子 ID 从数据库中提取数据并将其回显到 json 数组中,以便 objective-c 可以读取它并显示它。我的问题是我从不回显数据,因为帖子 ID 没有传输到 php 文件或者发生了其他事情。
我在其他文件中使用下面相同的 Objective-C 代码将数据发送和插入数据库,它工作正常,所以我不确定问题出在哪里。
这是我的 objective-c :
-(void) getData:(NSData *) data{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
-(void) start{
NSMutableString *postString = [NSMutableString stringWithString:kRecieveUrl];
[postString appendString:[NSString stringWithFormat:@"?%@=%@", kId, _post_id]];
[postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
[request setHTTPMethod:@"POST"];
postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
NSURL *url = [NSURL URLWithString:kRecieveUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
还有我的 php:
<?php
$db_connect = mysql_connect("localhost", "root", "")
or die("Our servers are down at the moment");
mysql_select_db("My DB") or die("Couldnt find db");
$post_id = $_GET['id'];
$query = "SELECT * FROM Comments WHERE post_id='$post_id'";
$results = mysql_query($query);
$num = mysql_numrows($results);
mysql_close();
$rows = array();
while($r = mysql_fetch_assoc($results))
{
$rows[] = $r;
}
echo json_encode($rows);
?>
最佳答案
尝试这样的事情
- (void)start {
NSMutableString *postString = [NSMutableString stringWithString:RecieveUrl];
[postString appendString:[NSString stringWithFormat:@"?%@=%@", kId, _post_id]];
[postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue currentQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
// do error handling
} else {
id json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error) {
// do error handling
} else {
// do something with json
}
}
}];
}
关于php - 将数据发送到 php 文件并根据该数据不工作 objective-c 从数据库中提取内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31055324/