如何从iOS向Php发送字符串和数据,以便在MySQL数据库中创建表


How to send a string and data from iOS to Php for creating a table in MySQL database

我正试图找到一种方法,将字符串和json数据文件传递给在线Php文件,该文件将使用字符串作为表名在MySQL数据库中创建一个表,并将json数据放入该表中。到目前为止,我在iOS端有以下代码:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"http://myWebAddress/uploadData.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:self.myData];
    NSURLSessionDataTask *sessionDataTask = [urlSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (error) {
            NSLog(@"%@", error);
        } else {
            self.textLabel.text=@"Data uploaded to database!";
        }
    }];
    [sessionDataTask resume];

在网络方面,我有以下Php代码:

<?php
$json_data=file_get_contents('php://input', true);
$post_data = json_decode($json_data);
$dbc=mysql_connect("mysql", "userName", "password");
mysql_select_db("myDatabase");
foreach($post_data as $lineData)
{$lastName=$lineData->lastName;
$firstName=$lineData->firstName;
$company=$lineData->company;
mysql_query("INSERT INTO `peopleDataTable` (`lastName`, `firstName`, `company`) VALUES ('$lastName', '$firstName', '$company')");}
mysql_close($dbc);
if (is_array($post_data))
$response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
$response = array("status" => "error", "code" => -1, "original_request" => $post_data);
$processed = json_encode($response);
echo $processed;
?>

你能帮我找到一个修改这些代码的解决方案吗?这样我就可以向Php发送一个字符串,并使用该字符串指定表名"peopleDataTable"?

或者我应该完全修改代码?

非常感谢!

Paul

请查看下面的链接以将数据作为参数传递,否则您可以使用AFNetwork进行数据传输,它有非常简单的方法。

http://hayageek.com/ios-nsurlsession-example/

-(void)requestFunction:(NSString *)main_url :(NSMutableDictionary *)parameters :(BOOL)post
{
     __block NSString *response_string;
     __block NSData *objectData;
     __block NSMutableDictionary *json;
    NSURL *baseURL=[NSURL URLWithString:BASE_URL];
    manager = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    if (post == NO)
    {
        [manager GET:main_url parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
         {
             response_string=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
             objectData = [response_string dataUsingEncoding:NSUTF8StringEncoding];
             NSError *jsonError;
             json = [NSJSONSerialization JSONObjectWithData:objectData
                                                    options:NSJSONReadingMutableContainers
                                                      error:&jsonError];
               [[self delegate] apiResponse:json];
            } failure:^(NSURLSessionDataTask *task, NSError *error)
                {
                      STOP_LOAD;
                       NSLog(@"%@",error);
                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Server Error, Please try again later"
                                                                 message:[error localizedDescription]
                                                                delegate:nil
                                                       cancelButtonTitle:@"Ok"
                                                       otherButtonTitles:nil];
                  [alertView show];
                  }];
    }
    else
    {
        [manager POST:main_url parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject)
        {
            response_string=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
            objectData = [response_string dataUsingEncoding:NSUTF8StringEncoding];
            NSError *jsonError;
            json = [NSJSONSerialization JSONObjectWithData:objectData
                                                   options:NSJSONReadingMutableContainers
                                                     error:&jsonError];
           // [self requestComplete:json];
               [[self delegate] apiResponse:json];
        }
              failure:^(NSURLSessionDataTask *task, NSError *error) {
                    NSLog(@"%@",error);
                    STOP_LOAD;
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Server Error,Please try again later"
                                                                               message:[error localizedDescription]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"Ok"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                  }];
    }

}

你可以看到我的代码,我只是像下面这样调用这个方法,

-(void)Login: (NSString *) User_fb_id
{
     NSMutableDictionary *api_call_parameter=[[NSMutableDictionary alloc] init];
      [api_call_parameter setObject:User_fb_id forKey:@"user_fb_id"];
      [api_call_parameter setObject:@"ios" forKey:@"device_type"];
      [api_call_parameter setObject:Device_Token forKey:@"device_id"];
      [self requestFunction:LOGIN :api_call_parameter :YES];
}

因此,您可以将数据作为参数通过该字典进行传递。