【问题标题】:Sending POST request from iOS to PHP server?将 POST 请求从 iOS 发送到 PHP 服务器?
【发布时间】:2016-01-12 17:33:40
【问题描述】:

当我尝试使用 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;

?>

请帮帮我

数据库截图

【问题讨论】:

  • 顺便说一下,getData 方法声明不符合标准方法签名。你应该做- (NSString *)getDataWithRequest:(NSMutableURLRequest *)request requestType:(NSString *)requestType data:(NSData *)data。然后将其称为[serverConnection getDataWithRequest:request requestType:@"POST" data:postData]
  • 我在下面更新了我的答案
  • 您在上面将Content-Type 设置为application/json 这是不正确的。下面,你根本不设置它。您可能希望将其设置为application/x-www-form-urlencoded。不需要设置Content-Type,但这是一种很好的做法。
  • 哦,好的,会更正那个..谢谢
  • 很抱歉用 cmets 来攻击你,但你也想在使用 SQL 中的值之前调用mysqli_real_escape_string。如果你不这样做,你就会面临 SQL 注入攻击。坦率地说,它看起来甚至不像 performing the query,所以也许你应该先解决这个问题,但请确保在执行 SQL 之前转义这些值。

标签: php ios mysql objective-c post


【解决方案1】:

尝试将您的 php 代码更改为以下内容(仅检查您是否获得了 post 值):

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

?>

如果您未正确发送值,此代码将返回错误消息(“未找到帖子值!”)。

【讨论】:

  • 所以你的 iOS 代码有问题。不幸的是,我不懂 iOS 编码。
  • :-) 我阅读了您的个人资料,非常感谢您的支持
  • 就像 OP 的代码一样,这会在构建 $sql 之前使用 mysqli_close 关闭数据库,而从不使用 performs the query
【解决方案2】:

终于它的工作了..这是我从 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
}

【讨论】:

  • 顺便说一句,如果您的任何参数包含任何保留字符(空格、&amp;+ 字符等),这将不起作用。您应该百分比转义这些值。您应该使用NSURLSession,因为NSURLConnection 现在已被弃用。例如,请参阅stackoverflow.com/questions/25701436/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-29
  • 2016-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多