1

everyone.

I'm working with my iOS App that connects to MySQL via PHP.

I want my App to send PHP GET request and get some data selected from MySQL database but I have no idea how to send data on MySQL to iOS. Here's my code.

myDataGetter.m

//create a request and connect (url is my PHP file's)
NSURLRequest* getRequest = [NSURLRequest requestWithURL:url];
NSURLConnection* connection = [NSURLConnection connectionWithRequest:getRequest      
                                                            delegate:self];
if (connection) {
    //data received from PHP will be stored in receivedData
    receivedData = [[NSMutableData alloc] init];
} else {
    //error
}

In myDataGetter.m I set delegate methods of NSURLConnection. For example,

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [receivedData setLength:0]
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data];
}

and in my PHP file,

$con = mysql_connect ('host', 'user', 'pass');
mysql_select_db ('dbname', $con);

$rows = mysql_query ("SELECT name, age, email FROM table");
while ($row = mysql_fetch_array ($rows)) {
    $name = $row["name"];
    $age = $row["age"];
    $email = $row["email"];
}

In this example, I want to send $name, $age, and $email to iOS. If you know how to do this, please help me.

Thank you.

nakazy
  • 31
  • 4
  • Where are U create connections iPhone with PHP server? – Sergey May 30 '12 at 08:31
  • @Sergey Thanks for your comment! I wrote connections in myDataGetter.m, which is a Subclass of UIViewController. In same ViewController I created and did addSubView: a UIButton and when I touch it down connection will start. – nakazy May 30 '12 at 09:35

1 Answers1

0

I always use ASIHTTPRequest for this sort of work. It's much more powerful than the NSURLConnection framework.

Secondly, I would use PHP to encode the results in JSON, and then use the really good SBJson framework for iOS to simply put the results of the request into an NSDictionary or NSMutableArray.

http://allseeing-i.com/ASIHTTPRequest/Setup-instructions

http://stig.github.com/json-framework/

JSON encode MySQL results

Community
  • 1
  • 1
derbs
  • 333
  • 3
  • 6