1

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

Bangalore
  • 1,572
  • 4
  • 20
  • 50
  • By the way, the `getData` method declaration doesn't conform to standard method signatures. You should do `- (NSString *)getDataWithRequest:(NSMutableURLRequest *)request requestType:(NSString *)requestType data:(NSData *)data`. And then call it as `[serverConnection getDataWithRequest:request requestType:@"POST" data:postData]`. – Rob Jan 12 '16 at 18:18
  • i updated my answer below – Bangalore Jan 12 '16 at 18:19
  • Above you set `Content-Type` to `application/json` which is not correct. Below, you don't set it at all. You probably want to set it to `application/x-www-form-urlencoded`. It's not required to set `Content-Type`, but it's good practice. – Rob Jan 12 '16 at 18:20
  • oh ok,, will correct that .. thanks – Bangalore Jan 12 '16 at 18:23
  • Sorry to barrage you with comments, but you also want to call [`mysqli_real_escape_string`](http://php.net/manual/en/mysqli.real-escape-string.php) before you use the values in SQL like that. If you don't, you open yourself to SQL injection attacks. Frankly, it doesn't look like you're even [performing the query](http://php.net/manual/en/mysqli.query.php), so maybe you should fix that first, but make sure you escape the values before performing the SQL. – Rob Jan 12 '16 at 18:28
  • can u make it as answer? please so i can follow – Bangalore Jan 12 '16 at 18:31
  • If you want to use `mysqli_real_escape_string` see http://stackoverflow.com/a/34103945/1271826. If you want to bind values manually see http://stackoverflow.com/a/27884399/1271826 (though ignore the fact that that one is expecting JSON request, but rather focus on how (a) it builds JSON response and (b) how it uses [`mysqli_stmt_bind_param`](http://php.net/manual/en/mysqli-stmt.bind-param.php) to bind values in the SQL). – Rob Jan 12 '16 at 18:39

2 Answers2

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.

Manikiran
  • 2,618
  • 1
  • 23
  • 39
  • So its something wrong with your iOS code. And unfortunately I don't know iOS coding. – Manikiran Jan 12 '16 at 17:47
  • 1
    :-) i read your profile and its pretty cool thanks for your support – Bangalore Jan 12 '16 at 17:48
  • Like the OP's code, this closes the database with `mysqli_close` before it even builds the `$sql` and never [performs the query](http://php.net/manual/en/mysqli.query.php). – Rob Jan 12 '16 at 18:45
0

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
}
Bangalore
  • 1,572
  • 4
  • 20
  • 50
  • 1
    By the way, this won't work if any of your parameters include any reserved characters (spaces, `&`, or `+` characters, etc.). You should percent escape the values. And you should use `NSURLSession`, as `NSURLConnection` is now deprecated. See http://stackoverflow.com/questions/25701436/how-to-make-post-nsurlrequest-with-2-parameters/25702239#25702239 for example. – Rob Jan 12 '16 at 18:24