我也是网络服务的新手。对于我的应用程序,我使用了此代码,我认为它可以在您的情况下采用:
-(IBAction)addData:(id)sender{
[self displayActivityIndicator];
NSString *studentName = self.studentNameTextField.text;
NSString *studentAddress = self.studentAddressTextField.text;
NSString *rollNumber = self.rollNumberTextField.text;
NSString *semesterType = self.semesterTypeTextField.text;
NSString *rawStr = [NSString stringWithFormat:@"name=%@&address=%@&&rollNumber=%@&semester=%@", studentName,
studentAddress,
rollNumber,
semesterType];
NSData *data = [rawStr dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:@"http://www.mywebsite.com/savedata.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:data];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSLog(@"%@", responseString);
NSString *success = @"success";
[success dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%lu", (unsigned long)responseString.length);
NSLog(@"%lu", (unsigned long)success.length);
[self dismissViewControllerAnimated:YES completion:nil]; // Dismiss the viewController upon success
}
保存数据.php
<?php
header('Content-type: text/plain; charset=utf-8');
$db_conn = new PDO('mysql:host=localhost;dbname=mydatabase','admin','password');
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$message = "";
$name = ($_POST['name']);
$address = ($_POST['address']);
$rollNumber = ($_POST['rollNumber']);
$semester = ($_POST['semester']);
$qry = $db_conn->prepare('INSERT INTO myTable(`name`,`address`,`rollNumber`,`semester`) VALUES (:name,:address,:rollNumber,:semester)');
$qry->bindParam(':name', $name);
$qry->bindParam(':address', $address);
$qry->bindParam(':rollNumber', $rollNumber);
$qry->bindParam(':semester', $semester);
$qry->execute();
if ($qry) { $message = "success"; }
else { $message = "failed"; }
echo utf8_encode($message);
?>