In my application, the user has the ability to post something and others can comment on it. Anyway, to view the post you see the title of it on a tableview which than pushes to a detail view. That segue carries the post id. To display the comments, I must send the post id to a php file. I then pull data from the database based on that post id and echo it in a json array so objective c can read it and display it. My problem is that I am never echoing the data because either the post id is not getting transferred to the php file or something else is happening.
I use the same objective c code below in other files to send and insert data into database and it works fine so I am not sure what the problem is.
Here is my 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];
}
And my 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);
?>
You're using the GET method so just delete the line [request setHTTPMethod:@"POST"];
, otherwise you would have to pass a dictionary containing the POST data
try something like this
- (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
}
}
}];
}