【问题标题】:Empty data while trying to send Post method request尝试发送 Post 方法请求时为空数据
【发布时间】:2015-08-06 06:00:28
【问题描述】:

我正在尝试向我发送 POST 方法请求,但是当发送帖子时,存储在数据库中的数据为空,我没有得到我发送的值,这是我尝试过的:

NSString *queryString = [NSString stringWithFormat:@"http://localhost/json/insertData.php?username=test&password=test"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString: queryString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[theRequest setHTTPMethod:@"POST"];
NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

一切都很好,只有当数据被发送并且我检查数据库时我得到了空值,请问错误在哪里。

这是我的 PHP 文件的代码:

<?php

    $host = "localhost";
    $user = "root";
    $pass = "root";
    $db   = "Users";


    $con = mysqli_connect($host,$user,$pass);

    if(!$con)
    {
        die("Can't connect to mysql server!");
    }

    $db_select = mysqli_select_db($con,$db);

    if(!$db_select)
    {
        die("Can't get the selected db!");
    }

    $id       = "11";
    $username = $_POST['username'];
    $password = $_POST['password'];
    $email    = "any1@any1.com";
    $gsm      = "91111111";

    $query = "INSERT INTO Logins VALUES($id,'$username','$password','$email',$gsm)";
    $query_exec = mysqli_query($con,$query);

    if(!$query_exec)
    {
        die("Can't insert data");
    }

?>

【问题讨论】:

  • 请添加您的insertData.php的相关代码。
  • 好的,问题已编辑,代码已添加

标签: php ios objective-c xcode xcode5


【解决方案1】:

您正在通过 GET 传递变量 usernamepassword。在您的 PHP 脚本中,您必须使用 $_GET 而不是 $_POST

$username = $_GET['username'];
$password = $_GET['password'];

【讨论】:

【解决方案2】:

在您的错误网址中显示

http://localhost/json/insertData.php?username=test&amp;password=test

您可以清楚地看到username=test&amp;password=test 拥有所有数据。这意味着你的表格method="get"

所以在你的代码中

$username = $_GET['username'];
$password = $_GET['password'];

这将解决您的问题。

【讨论】:

  • 我不想使用 get,我想通过一个 post 表单我该怎么做?
  • 检查您的提交操作
【解决方案3】:

更具体地说,在上一页的表单中,您应该将提交表单标记更改为包含 method="post"。

<form method="post">

【讨论】:

    【解决方案4】:

    由于这个问题没有答案,您还告诉我,我将 $_POST 请求更改为 $_GET,但正如我所说,我希望它发布而不是 GET。最后我得到了错误,我必须使用此代码对 DATA 进行编码:

    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    

    添加此代码后,数据添加成功。

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 1970-01-01
      • 2020-02-29
      • 2019-11-11
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多