我不确定如何从Objective-C运行PHP脚本来检索用于查询数据库的GET数据。是否可以直接从Objective-C从PHP脚本执行和检索返回的数据?更好的是,是否存在直接从iOS / Objective-C查询MySQL数据库服务器的功能?任何想法表示赞赏。
杰克
您可以直接从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];
}
就是这样,我希望能对您有所帮助
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句