Insert data into remote mysql database by POST method from iOS device

后端 未结 3 1292
故里飘歌
故里飘歌 2021-01-14 20:26

I have 3 values :

  • id
  • name
  • email

I have three UIText field where i can give these input and save these values into

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-14 20:38

    You can use the NSURLSessionDataTask function to post data up to PHP and get a response with JSON.

    - (IBAction)saveButton:(id)sender
    {
    
    NSString *noteDataString = [NSString stringWithFormat:@"name=%@&email=%@", nameTextField.text, emailTextField.text];
    
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mydomain.com/iOS/Tulon/phpFile.php"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[noteDataString dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *dataRaw, NSURLResponse *header, NSError *error) {
    NSDictionary *json = [NSJSONSerialization
                                  JSONObjectWithData:dataRaw
                                  options:kNilOptions error:&error];
    NSString *status = json[@"status"];
    
    if([status isEqual:@"1"]){
    //Success
    
    } else {
    //Error
    
    }
    }];
    
    [dataTask resume];
    }
    

    and you can handle the response in PHP with this code:

     '1');                 
    } else {
    die("Query failed");
    }
    
    echo json_encode($res);
    exit();
    ?>
    

    Hope this helps

提交回复
热议问题