从iOS设备通过POST方法将数据插入远程mysql数据库
我有3个值:
- ID
- 名称
- 电子邮件
我有三个UIText
字段,我可以给这些input并将这些值保存到远程数据库。 我使用GET
方法来完成它。 我没有问题。 但是,如果我想用POST
方法做同样的事情,那我该怎么做。 我想下面现有的代码会有一些变化。 如果有人知道解决scheme,请与我分享。 很多感谢提前。 祝你今天愉快。 🙂
iOS部分代码:
- (IBAction)saveButton:(id)sender { NSString *strURL = [NSString stringWithFormat:@"http://mydomain.com/iOS/Tulon/phpFile.php?name=%@&email=%@", nameTextField.text, emailTextField.text]; NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]; NSLog(@"strResult %@", strResult); nameTextField.text = nil; }
远程服务器部分代码:
<?php /* ----------------------------- Code for Dabase ----------------------------- */ // Database Properties $dbhost = 'mydomain.com'; $dbuser = 'username'; $dbpass = 'password'; $db = 'dbName'; $dbtable = 'user'; // Connect Database $conn = mysql_connect($dbhost,$dbuser,$dbpass) or die (mysql_error()); mysql_select_db($db, $conn) or die(mysql_error()); /* ----------------------------- Code for Dabase ----------------------------- */ if (isset ($_GET["name"]) && isset ($_GET["email"])) { $name = $_GET["name"]; $email = $_GET["email"]; } else { $name = "Tulon"; $email = "tulon@yahoo.com"; } // Insert value into DB $sql = "INSERT INTO $dbtable (id, name, email) VALUES (NULL, '$name', '$email');"; $res = mysql_query($sql,$conn) or die(mysql_error()); mysql_close($conn); if ($res) { echo "success"; } else { echo "faild"; } ?>
您可以使用NSURLSessionDataTask函数将数据发布到PHP,并使用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]; }
你可以用这个代码在PHP中处理响应:
<?php if (isset ($_POST["name"]) && isset ($_POST["email"])){ $name = $_POST["name"]; $email = $_POST["email"]; } else { $name = "Tulon"; $email = "tulon@yahoo.com"; } // Insert value into DB $sql = "INSERT INTO $dbtable (name, email) VALUES ('$name', '$email');"; $res = mysql_query($sql,$conn) or die(mysql_error()); mysql_close($conn); if($res) { $response = array('status' => '1'); } else { die("Query failed"); } echo json_encode($res); exit(); ?>
希望这可以帮助
你能试试吗? 可能对你有用。
NSString *strURL = [NSString stringWithFormat:@"name=%@&email=%@", nameTextField.text, emailTextField.text]; NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://mydomain.com/iOS/Tulon/phpFile.php"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"]; [request setHTTPBody:postData]; NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; if(conn) { NSLog(@"Connection Successful"); } else { NSLog(@"Connection could not be made"); }
在这个实现下面的方法得到响应之后
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)d { [self.ask_data appendData:d]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *responseText = [[NSString alloc] initWithData:self.ask_data encoding:NSUTF8StringEncoding]; NSLog(@"response=%@",responseText); }
我有一个类似的方式更新我的数据库的问题….
Sql语句
<?php // Create connection $con=mysqli_connect("server_name","user_name","user_code","table_name"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // This SQL statement selects ALL from the table 'table.name' $sql = "SELECT * table_name"; // Check if there are results if ($result = mysqli_query($con, $sql)) { // If so, then create a results array and a temporary one // to hold the data $resultArray = array(); $tempArray = array(); // Loop through each row in the result set while($row = $result->fetch_object()) { // Add each row into our results array $tempArray = $row; array_push($resultArray, $tempArray); } // Finally, encode the array to JSON and output the results echo json_encode($resultArray); } $sql = "INSERT INTO table_name (column_name) VALUES('1')"; // Close connections mysqli_close($result); mysqli_close($con); ?>
我的iOS代码
for (Tickets *items in _feedItems){ if ([resultText.text isEqual:(id) items.ticketNumber]) { status.text = @"Match found"; //Contacting database------------------------------ NSString *strURL = [NSString stringWithFormat:@"TicketDate=%@", items.ticketDate]; NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:@"http://webservice.com"]]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current- Type"]; [request setHTTPBody:postData]; NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self]; if(conn) { NSLog(@"Connection Successful"); } else { NSLog(@"Connection could not be made"); } //Contacting database END------------------------------------------- break; }else { status.text = @"Match not found"; } }
我从NSLog得到一个Connection Succesful,但没有任何更新在我的数据库中。
我试图手动input一个应用程序的门票号码,如果它与数据库中的门票相匹配(它的工作原理),那么我想让ticketDate从0更改为1。
但它不会改变:/