【问题标题】:From PHP Webservice not returning encode response correclty从 PHP Web 服务未正确返回编码响应
【发布时间】:2015-11-17 06:36:31
【问题描述】:

我编写了简单的 PHP 代码来从我的 iphone 应用程序中注册用户详细信息。它工作正常并返回 JSON 输出。我在下面添加了该代码

header('Content-type: application/json');
include 'connection.php';
$response = array();

$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

if($username == NULL || $password == NULL || $email == NULL ){

    $response["success"] = 0;
    $response["message"] = "Something Empty";

}else{

    $sql = "INSERT INTO User (username, password, email)
VALUES ('".$username."', '".$password."', '".$email."')";

if ($conn->query($sql) === TRUE) {

    $response["success"] = 1;
    $response["message"] = "Done";

} else {

    $response["success"] = 0;
    $response["message"] = "Error";
}
}

echo json_encode($response);
$conn->close();

但是当我尝试在添加到表之前检查用户名已经存在时。我从我的 Xcode 日志中收到错误消息。

JSON text did not start with array or object and option to allow fragments not set.

if($username == NULL || $password == NULL || $email == NULL ){

    $response["success"] = 0;
    $response["message"] = "Something Empty";

}else{

   $query = mysql_query("SELECT * FROM User WHERE username='".$username."'");


    if (mysql_num_rows($query) != 0)
  {
      $response["success"] = 0;
      $response["message"] = "Username Already Exists";

  }else{

      $response["success"] = 1;
      $response["message"] = "That Name Fine";
  }


}

【问题讨论】:

    标签: php ios json xcode afnetworking


    【解决方案1】:

    很可能是 php 错误(可能只是通知或警告,具体取决于您的 error_reporting 设置)污染了 json 输出。

    您需要调试问题,并且可以考虑将error_reporting 级别用于生产。

    【讨论】:

    • $query = mysql_query("SELECT * FROM User WHERE username='".$username."'"); 会在调用if (mysql_num_rows($query) != 0)之前输出一些东西
    • 你是用mysql还是mysqli连接?
    • 那是你的错误。你用过mysql_query()
    • 太棒了。是的,它解决了这个问题。我根据mysqli改了代码
    • mysql 已贬值,因此您绝对应该使用 mysqli。 mysqli 还支持更多的选项和功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多