Tulon
Tulon

Reputation: 4136

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

I have 3 values :

I have three UIText field where i can give these input and save these values into a remote database. I use GET method to accomplish it. And i have no problem. But, if i want to do the same thing with POST method then how can i do that. I think there will be a little change in the current existing code below. Please share with me if any one know the solution. A lot of thanks in advance. Have a nice day. :)

Code of iOS section :

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

Code of Remote server section :

<?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 = "[email protected]";
    }

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

Upvotes: 2

Views: 9098

Answers (3)

user3753385
user3753385

Reputation: 37

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

Sql statements

<?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 Succesful from the NSLog but there is nothing getting updated in my database.

I'm trying to manually type in a ticket number with an app, and if that matches with a ticket in the database (it works), then I want the the ticketDate to change from 0 to 1.

But it does not change :/

Upvotes: 1

George Grover
George Grover

Reputation: 1134

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:

<?php
if (isset ($_POST["name"]) && isset ($_POST["email"])){
    $name = $_POST["name"];
    $email = $_POST["email"];
} else {
    $name = "Tulon";
    $email = "[email protected]";
}

// 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

Upvotes: 4

Bhoopi
Bhoopi

Reputation: 6593

Can you try this? may be it 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 this implement following methods to get 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);
}

Upvotes: 1

Related Questions