从iOS发送POST请求到PHP服务器?

时间:2016-01-12 17:33:41

标签: php ios mysql objective-c post

当我尝试使用PHP服务器注册我的用户表单iOS时,总是在mysql db中添加空行。

当我从php打印变量值时为空。

这是我的代码

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

}

从php结果获得成功但总是空值是addin ginto db。

我的PHP代码

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

?>

请帮帮我

db截图 enter image description here

2 个答案:

答案 0 :(得分:1)

尝试将您的PHP代码更改为以下内容(只是检查您是否获得了帖子值):

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

?>

如果您没有正确发送值,此代码将返回错误消息(“找不到发布的值!”)。

答案 1 :(得分:0)

最后它的工作......这是我从ios方面改变了

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