iOS/Objective-C - 如何从iPhone应用程序查询Web服务器数据库?

Jak*_*man 3 database iphone service ios web

我不确定如何从Objective-C运行PHP脚本来检索用于查询数据库的GET数据.有没有办法直接从Objective-C执行和检索来自PHP脚本的返回数据?更好的是,是否有直接从iOS/Objective-C查询MySQL数据库服务器的功能?任何想法都表示赞赏.

可靠的人

Ila*_*rio 5

您可以直接从objective-c安全地查询mysql数据库.

你必须创建一个像这样的PHP代码:

<?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);

?>
Run Code Online (Sandbox Code Playgroud)

这是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];


 }
Run Code Online (Sandbox Code Playgroud)

就是这样,我希望能帮到你