Jake Byman Jake Byman -4 years ago 64
iOS Question

iOS/Objective-C - How do I query a web server database from an iPhone app?

I'm not sure how to run a PHP script from Objective-C to retrieve GET data for querying a database. Is there a way to execute and retrieve returned data from a PHP script directly from Objective-C? Better yet, is there functionality to query a MySQL database server directly from iOS/Objective-C? Any thoughts are appreciated.

Jake

Answer Source

you can safely query a mysql database, directly from objective-c.

you must create a php code like this:

<?php
$con = mysql_connect("server", "username", "password");
if (!$con)
{
 die('Could not connect: ' . mysql_error());
}

mysql_select_db("username_numberOfTable", $con);

$query = mysql_query("SELECT id, Name, Type FROM table") 
or die ('Query is invalid: ' . mysql_error());

$intNumField = mysql_num_fields($query);
$resultArray = array();

while ($row = mysql_fetch_array($query)) {

$arrCol = array();
for($i=0;$i<$intNumField;$i++)
   {

    $arrCol[mysql_field_name($query,$i)] = $row[$i];

} 

array_push($resultArray,$arrCol);

}

mysql_close($con);

echo json_encode($resultArray);

?>

and this is the part of objective-c:

- (void)viewDidLoad {

  NSString *stringName = @"Name";
  NSString *stringType = @"Type";

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL    URLWithString:@"http://yourURL.php?"]];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest  delegate:self];
 }

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

[receivedData appendData:data];

 }

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

if (receivedData) {

      id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];

    for (NSDictionary *dataDict in jsonObjects) {

        NSString *stringNameID = [dataDict objectForKey:@"Name"];
        NSString *stringTypeID = [dataDict objectForKey:@"Type"];


    dict = [NSDictionary dictionaryWithObjectsAndKeys:stringNameID, stringName, stringTypeID, stringType, nil];

        [yourNSMutableArray addObject:dict];


    }

   [self.tableView reloadData];

 }

}


 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  {

 NSDictionary *tmpDict = [yourNSMutableArray objectAtIndex:indexPath.row];

cell.textLabel.text = [tmpDict objectForKey:stringName];
cell.detailTextLabel.text = [tmpDict objectForKey:stringType];


 }

and that's it, I hope can I help

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download