duandianzhong8315 2015-12-23 04:21
浏览 45
已采纳

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

I'm trying to find a way to pass a string and a json data file to an online Php file, which will create a table in a MySQL database using the string as the table name, and put the json data into the table. So far I have the following code on the iOS side:

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

On the web side, I have the following Php code:

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

Could you help me to find a solution to modify this codes so that I can send a string to the Php, and use the string to specify the table name "peopleDataTable"?

Or I should completely modify the code?

Thank you very much!

Paul

  • 写回答

1条回答 默认 最新

  • doucong8553 2015-12-23 04:52
    关注

    Please review the below link to pass data as parameter , else you can use AFNetwork for data transfer which has pretty easy methods.

    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];
    
                      }];
        }
    
    
    }
    

    You can see my code , i just call this method like below,

    -(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];
    }
    

    So you can pass the data through this dictionary as parameter.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,