3

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

杰克

4

2 回答 2

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

?>

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


 }

就是这样,我希望能帮上忙

于 2013-10-01T07:38:02.830 回答
1

有两种类型的服务可用于将数据发送到 Web 服务器:

  1. 同步 NSURL 请求

  2. 异步 NSURL 请求

如果您只想将数据发布到 Web 服务器,请使用异步请求,因为它在后台工作并且不会阻塞用户界面。

NSString *content = @"txtfiedl.text=1";

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.ex.com/yourfile.php"]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];

[NSURLConnection connectionWithRequest:request delegate:self];
于 2013-10-01T06:09:42.990 回答