Bangalore
Bangalore

Reputation: 1580

Sending POST request from iOS to PHP server?

When i try to register my user form iOS using PHP server , am always getting empty row added in mysql db.

When i print variable value from php its empty.

This is my code

-(void)sendLogininfoToServer{
    NSUserDefaults *login = [NSUserDefaults standardUserDefaults];
    NSString *name=[login stringForKey:@"name"];
    //NSString *image=[login stringForKey:@"image"];
    NSString *email=[login stringForKey:@"email"];


    serverConnection=[[serverRequestProtocol alloc]init];
    serverConnection.delegate=self;
    //NSLog(@"get doc list%@",stringValue);
    NSString *url=@"http://example.in/php/signup.php";
    NSString *post = [NSString stringWithFormat:@"fname=%@&email=%@&country=%@&city=%@",name,email,@"India",@"Bangalore"];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSMutableURLRequest *request =[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString: url]];
    NSString *serverOutput=[serverConnection getData:request :@"POST":postData];

    NSLog(@"%@",serverOutput);

}



-(NSString *)getData:(NSMutableURLRequest *)request:(NSString *)requestType:(NSData *)data{
    [request setHTTPMethod:requestType];
    NSInteger millisecondsFromGMT = 1000 * [[NSTimeZone localTimeZone] secondsFromGMT];
    NSString *str1=[NSString stringWithFormat:@"%ld",millisecondsFromGMT];
    [request setHTTPBody:data];
    [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"iphone" forHTTPHeaderField:@"X-User-agent"];
    [request setValue:str1 forHTTPHeaderField:@"X-TimeZoneOffset"];
    NSURLResponse *response;
    NSError *err;
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
    NSString * serverOutput= [[NSString alloc]initWithData:returnData encoding:NSASCIIStringEncoding];
    return serverOutput;

}

Am getting success form php result but always empty values are addin ginto db.

my php code

<?php
header("Content-type: text/html; charset=utf-8"); 
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$charset="UTF8";
$name=$_POST['fname'];
$email=$_POST['email'];
$country=$_POST['country'];
$city=$_POST['city'];

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


/* change character set to utf8 */
if (!mysqli_set_charset($conn, "utf8")) {
    printf("Error loading character set utf8: %s\n", mysqli_error($conn));
    exit();
} else {
    mysqli_close($link);$sql = "INSERT INTO `basicinfo`(`fname`, `email`,`country`, `city`) VALUES ('$name','$email','$country','$city')";
if ($conn->query($sql) === TRUE) {
    echo $name;
} else {
    echo "fail";
}
}

exit;

?>

Please help me

db screenshot enter image description here

Upvotes: 1

Views: 1166

Answers (2)

Bangalore
Bangalore

Reputation: 1580

Finally its working..this is what i have changed from ios side

-(void)sendLogininfoToServer{
    NSUserDefaults *login = [NSUserDefaults standardUserDefaults];
    NSString *name=[login stringForKey:@"name"];
    //NSString *image=[login stringForKey:@"image"];
    NSString *email=[login stringForKey:@"email"];


    NSString *url=@"http://example.in/signup.php";
       NSString *stringData = [NSString stringWithFormat:@"fname=%@&email=%@&country=%@&city=%@",name,email,@"India",@"Bangalore"];
    NSLog(@"%@",stringData);
    NSURL *aUrl = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];
    [request setHTTPBody:[stringData dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Did Receive Response %@", response);
   responseData = [[NSMutableData alloc]init];
}

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    //NSLog(@"Did Receive Data %@", data);
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    NSLog(@"Did Fail");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Did Finish");
    NSString *strData=[[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];

    NSLog(@"Responce:%@",strData);
    // Do something with responseData
}

Upvotes: 0

Manikiran
Manikiran

Reputation: 1

Try changing your php code to the following (just checking if you are getting post values):

<?php
header("Content-type: text/html; charset=utf-8"); 
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "dbname";
$charset="UTF8";

if((isset($_POST['fname']))&&(isset($_POST['email']))&&(isset($_POST['country']))&&(isset($_POST['city'])))
{
    $name=$_POST['fname'];
    $email=$_POST['email'];
    $country=$_POST['country'];
    $city=$_POST['city'];

    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }


    /* change character set to utf8 */
    if (!mysqli_set_charset($conn, "utf8")) {
        printf("Error loading character set utf8: %s\n", mysqli_error($conn));
        exit();
    } else {
        mysqli_close($link);$sql = "INSERT INTO `basicinfo`(`fname`, `email`,`country`, `city`) VALUES ('$name','$email','$country','$city')";
    if ($conn->query($sql) === TRUE) {
        echo $name;
    } else {
        echo "fail";
    }
    }
}
else
{
    echo "no post values found!";
}

exit;

?>

This code will return error message ("no post values found!") if you are not sending values correctly.

Upvotes: 1

Related Questions