iphone - tutorial - xcode連接資料庫



iOS/Objective-C-如何從iPhone應用程序查詢Web服務器數據庫? (2)

您可以直接從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];


 }

就是這樣,我希望我能幫上忙

https://code.i-harness.com

我不知道如何從Objective-C運行PHP腳本來檢索GET數據來查詢數據庫。 有沒有一種方法可以直接從Objective-C執行並從PHP腳本中檢索返回的數據? 更好的是,是否有功能直接從iOS / Objective-C查詢MySQL數據庫服務器? 任何想法表示讚賞。

可靠的人


有兩種類型的服務可用於將數據發送到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];




web