php - Xcode在mysql数据库中编辑和添加数据

标签 php ios mysql xcode edit

我回到了几年前在 Xcode 中开始的一个项目。这是我的第一个 Xcode 项目,需要相当长的学习时间,但我最终让该应用程序按预期运行。我现在已经返回项目以添加一些功能,但是我无法返回并准确理解我的代码是如何运行的。该应用程序现在所做的基本上是与 mySQL 数据库通信,并显示数据库中用户选择的任何位置的数据。我现在想添加一个功能,用户可以在其中编辑此数据/将数据添加到数据库中。到目前为止,我一直找不到任何有用的教程或解决方案。这是我用于存储数据库数据的代码。

//
//  City.h
//  webView
//
//  Created by 1234 on 14-04-07.
//  Copyright (c) 2014 1234. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface City : NSObject
@property (nonatomic, strong)NSString * cityName;
@property (nonatomic, strong)NSString * clubName;
@property (nonatomic, strong)NSString * clubLine;
@property (nonatomic, strong)NSString * cityID;
@property (nonatomic, strong)NSString * cityCountry;
@property (nonatomic, strong)NSString * price;
@property (nonatomic, strong)NSString * camera;
@property (nonatomic, strong)NSString * taxi;
@property (nonatomic, strong)NSString * promo;
@property (nonatomic, strong)NSNumber * Latitude;
@property (nonatomic, strong)NSNumber * Longitude;

-(id)initWithCityName: (NSString *)cName andCityCountry: (NSString *)cCountry andClubName:   (NSString *)clName  andClubLine: (NSString *)cLine andPrice: (NSString *)pri andPromo: (NSString *)prom andCamera: (NSString *)cam andTaxi:(NSString *)taxi andLatitude: (NSNumber *)cLatitude andLongitude: (NSNumber *)cLongitude andCityId: (NSString *)cID ;


@end

//

//
//  City.m
//  webView
//
//  Created by 1234 on 14-04-07.
//  Copyright (c) 2014 1234. All rights reserved.
//

#import "City.h"

@implementation City
@synthesize cityCountry, cityID, Latitude, Longitude, cityName, clubName, clubLine,taxi,     price,promo,camera;

-(id)initWithCityName: (NSString *)cName andCityCountry: (NSString *)cCountry andClubName:     (NSString *)clName  andClubLine: (NSString *)cLine andPrice: (NSString *)pri andPromo: (NSString *)prom andCamera: (NSString *)cam andTaxi:(NSString *)tax andLatitude: (NSNumber *)cLatitude andLongitude: (NSNumber *)cLongitude andCityId: (NSString *)cID ;
{
self=[super init];
if(self)
{
    cityName=cName;
    cityCountry=cCountry;
    clubName= clName;
    clubLine=cLine;
    price=pri;
    promo=prom;
    camera=cam;
    Latitude= cLatitude;
    Longitude= cLongitude;
    cityID=cID;
    taxi= tax;


}
return self;
}


@end

//-(void)retrieveData将数据存储在jsonArray中

//
//  ViewController.m
//  webView
//
//  Created by 1234 on 14-04-06.
//  Copyright (c) 2014 1234. All rights reserved.
//

#import "ViewController.h"
#import "DetailController.h"
#import "Annotation.h"


#import "City.h"

@interface ViewController (){
MKLocalSearch *localSearch;
MKLocalSearchResponse *results;
}
@property (nonatomic, strong) IBOutlet DetailController *detailViewController;



@end
#define getDatalURL @"http://www.club-hop.com/apptest.php"

@implementation ViewController

@synthesize mapView,jsonArray,citiesArray;

- (void)viewDidLoad
{
[super viewDidLoad];

[self retrieveData];
self.edgesForExtendedLayout=UIRectEdgeNone;
self.detailViewController = [[DetailController alloc] init];
[self.searchDisplayController setDelegate:self];
[self.ibSearchBar setDelegate:self];
//Zoom the map to current location.
[self.mapView setShowsUserLocation:YES];
[self.mapView setUserInteractionEnabled:YES];
[self.mapView setUserTrackingMode:MKUserTrackingModeFollow];

City * cityObject;

// load external page into UIWebView
NSMutableArray * locations= [[NSMutableArray alloc]init];
CLLocationCoordinate2D location;
Annotation * myAnn;

for(int u=0; u<citiesArray.count;u++){
    cityObject=[citiesArray objectAtIndex:u];

    myAnn=[[Annotation alloc]init];

    myAnn.city=cityObject;     // Store the city object on the annotation

    NSNumber *aLat= cityObject.Latitude;
    NSNumber *aLon= cityObject.Longitude;
    NSString *cab= cityObject.taxi;

    double lat = [aLat doubleValue];
    double lon = [aLon doubleValue];

    location.latitude= lat;
    location.longitude=lon;
    myAnn.coordinate = location;
    myAnn.title=cityObject.clubName;
    myAnn.subtitle=cityObject.cityName;

    [locations addObject:myAnn];}

[self.mapView addAnnotations:locations];


}



- (BOOL)prefersStatusBarHidden
{
return YES;
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}



//class methods
-(void) retrieveData{

NSURL * url= [NSURL URLWithString:getDatalURL];
NSData * data= [NSData dataWithContentsOfURL:url];
jsonArray= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

//setup cities array
citiesArray=[[NSMutableArray alloc]init];

for(int i=0; i<jsonArray.count;i++){
    NSString * cID= [[jsonArray objectAtIndex:i] objectForKey:@"id"];
    NSString * cName= [[jsonArray objectAtIndex:i] objectForKey:@"cityName"];
    NSString * cCountry= [[jsonArray objectAtIndex:i] objectForKey:@"cityCountry"];
    NSString * cLine= [[jsonArray objectAtIndex:i] objectForKey:@"clubLine"];
    NSString * pri=[[jsonArray objectAtIndex:i] objectForKey:@"price"];
    NSString * promo=[[jsonArray objectAtIndex:i] objectForKey:@"promo"];
    NSString * camera=[[jsonArray objectAtIndex:i] objectForKey:@"camera"];
    NSString * taxi= [[jsonArray objectAtIndex:i] objectForKey:@"Taxi"];
    NSString * clName= [[jsonArray objectAtIndex:i] objectForKey:@"clubName"];
    NSNumber * cLatitude= [[jsonArray objectAtIndex:i] objectForKey:@"Latitude"];
    NSNumber * cLongitude= [[jsonArray objectAtIndex:i] objectForKey:@"Longitude"];

    [citiesArray addObject:[[City alloc]initWithCityName:cName andCityCountry:cCountry   andClubName:clName andClubLine:cLine andPrice:pri andPromo:promo andCamera:camera andTaxi:taxi andLatitude:cLatitude andLongitude:cLongitude andCityId:cID]];

}

}


#pragma mark - MKMapViewDelegate

// user tapped the disclosure button in the callout
//
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view  calloutAccessoryControlTapped:(UIControl *)control

{   

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                     bundle:nil];
self.detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"Page2"];

Annotation *myAnnotation=(Annotation *)view.annotation;


self.detailViewController.city=myAnnotation.city;


[self.navigationController pushViewController:self.detailViewController animated:YES];


}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView *pin=nil;
if ([annotation isKindOfClass:[Annotation class]])
{
    pin=(MKAnnotationView *)[mapView   dequeueReusableAnnotationViewWithIdentifier:@"myAnnotation"];
    if (pin == nil)
    {
        pin=[[MKAnnotationView alloc] initWithAnnotation:annotation   reuseIdentifier:@"myAnnotation"];
        pin.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        pin.image=[UIImage imageNamed:@"mappin.png"];
        pin.centerOffset=CGPointMake(0.0, pin.image.size.height/-2);
        pin.canShowCallout=YES;
    }
}
return pin;
}



#pragma mark - Search Methods

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {

// Cancel any previous searches.
[localSearch cancel];

// Perform a new search.
MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = searchBar.text;
request.region = self.mapView.region;

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];

[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    if (error != nil) {
        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Map Error",nil)
                                    message:[error localizedDescription]
                                   delegate:nil
                          cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil]   show];
        return;
    }

    if ([response.mapItems count] == 0) {
        [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No Results",nil)
                                    message:nil
                                   delegate:nil
                          cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil]  show];
        return;
    }

    results = response;

    [self.searchDisplayController.searchResultsTableView reloadData];
}];
} 



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [results.mapItems count];
}




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

static NSString *IDENTIFIER = @"SearchResultsCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:IDENTIFIER];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:IDENTIFIER];
}

MKMapItem *item = results.mapItems[indexPath.row];

cell.textLabel.text = item.name;
cell.detailTextLabel.text = item.placemark.addressDictionary[@"Street"];

return cell;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self.searchDisplayController setActive:NO animated:YES];

MKMapItem *item = results.mapItems[indexPath.row];


[self.mapView setCenterCoordinate:item.placemark.location.coordinate animated:YES];

[self.mapView setUserTrackingMode:MKUserTrackingModeNone];

}



@end

同样,我现在想做的是接收用户的输入并编辑从 http://club-hop.com/apptest.php 检索的数据。 .任何帮助将不胜感激

最佳答案

好的,所以从 iOS 向 SQL DB 添加数据是小菜一碟!当谈到上传数据时,iOS 并没有做太多工作,您只需使用 HTTP POST 函数将数据发送到服务器上的 PHP 文件,然后 PHP 就可以完成繁重的工作!我现在给你一个例子:

NSString *urlString = [NSString         stringWithFormat:@"http://www.example.com/postVar.php?var=%@", hold];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    NSMutableData *body= [NSMutableData data];

    [request setHTTPBody:body];
    NSError * e;
    NSURLResponse *string;

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&string error:&e];
    NSString* returnString= [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", returnString);

现在对于 PHP,这将是一个名为 postVar.php 的文件

<?php
//Set Server Details
$servername = "localhost";
$username = "tester";
$dbname = "myDB";
$password = "passw0rd";
/*For security reasons, you should get your password from iOS as well, using a GET     function, but this is easier for a demo.*/
//Get Value From iOS
$var = $_GET['var'];


//SQL

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
 }


 $sql = "INSERT INTO tablename (UserVariable) VALUES ('$var')";

 if (mysqli_query($conn, $sql)) {
  echo "Awesome. This works!"; 
  //This is what your app will receive as the variable returnData


 } else {
 echo "Oops. Error!"; 
 }

 mysqli_close($conn);
?>

关于php - Xcode在mysql数据库中编辑和添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27183951/

相关文章:

javascript - 只是想确保我做的事情是对的

ios - 仅在设备(iphone 和 ipad)上发生错误 - 链接器命令失败

iphone - 在后台调用函数和在线程中调用函数的区别

ios - 无法在 Xcode 中使用 iOS 发行版

php - 如何在删除表中的一行时删除所有相关的表记录?

javascript - 我想更改数据表按钮名称

php - 防止自动谷歌缩短 URL 访问

mysql - 如何从表中获取记录列表,其中使用 DATEDIFF 函数在选择查询本身的 2 个变量之间找到时间差?

php - 优化许多 "BETWEEN ? AND ?"where 子句

php - PHP中两个日期之间所有月份和年份的列表