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

I have 3 values:

  • ID
  • name
  • Email

I have three UIText fields where I can give this data and store these values ​​in a remote database. For this, I use the GET method. And I have no problem. But if I want to do the same with the POST method, then how can I do it. I think there will be a slight change in the current existing code. Please share with me if anyone knows the solution. Thank you very much in advance. Have a nice day.:)

IOS section code:

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

Remote Server Code:

 <?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"; } ?> 
+2
source share
3 answers

You can use the NSURLSessionDataTask function to publish data before PHP and receive a response using 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 process the response in PHP with this code:

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

Hope this helps

+4
source

You may try? perhaps this works for you.

 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"); } 

After that, follow these methods to get a response

 - (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); } 
+1
source

I have a problem updating my database in a similar way.

Sql Operators

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

My iOS code

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

I get a connection from NSLog but nothing is updated in my database.

I am trying to manually enter the ticket number with the application, and if this matches the ticket in the database (it works), then I want the ticketDate property to change from 0 to 1.

But this does not change: /

+1
source

Source: https://habr.com/ru/post/909636/


All Articles