我用的是alamofire,结果不一样

I used alamofire, but the result is different

我将值放入我的 url 并在请求时获取 true 或 false 文本的值。

func getHistoryCheck() {
    let urlString = "http://myphpfile.php?value1=" + value1 + "&value2=" + value2
    print(urlString)
    
    if let encoded = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let myURL = URL(string: encoded) {
        AF.request(myURL, method: .get).responseJSON { (myresponse) in
            switch myresponse.result {
            case .success:
                print("myresponse: ")
                print(myresponse)
                
            case .failure:
                print("Error")
            }
        }
    }
}

但是当我输入请求值时,这些结果就出来了。

myresponse: 
success(0)

我请求的值的结果应该是错误的。

然而,success(0)出来了。

success(0)是什么意思?

++ 我的 php 文件。

<?php

require_once 'connect.php';

$value1 = $_GET['value1'];
$value2 = $_GET['value2'];
$query = "SELECT EXISTS(SELECT id, name FROM nametable
WHERE id='$value1' AND name='$value2');";
$result = mysqli_query($con, $query);

if(!$result) {
    echo 'query error';
} else {
    $row = mysqli_fetch_row($result);
    if($row[0] == 0) {
        echo 'false';
    } else {
        echo 'true';
    }
}

mysqli_close($con);
?>

我建议不要使用查询参数手动构建 URL,而是让 Alamofire 为您完成。我建议检索与 .success.failure;

关联的值
func getHistoryCheck(value1: String, value2: String) {
    let parameters = [
        "value1": value1,
        "value2": value2
    ]

    AF.request(url, parameters: parameters)
        .validate()
        .responseJSON { response in
            switch response.result {
            case .success(let value):
                print("value:", value)

            case .failure(let error):
                if let data = response.data, let string = String(data: data, encoding: .utf8) {
                    print(string) // sometimes, if there is a server error, the HTML contains useful diagnostic info
                }
                print(error)
            }
        }
}

顺便说一句,我会添加 validate 以便它将非 2xx 状态代码捕获为错误。


在 PHP 方面,我建议将值绑定到 ? 占位符以避免 SQL 注入攻击。

<?php

// 

header('Content-type: application/json');

$value1 = $_REQUEST["value1"];
$value2 = $_REQUEST["value2"];

if (!(isset($value1) && isset($value2))) {
    http_response_code(422);
    $response = array("success" => false, "message" => "'value1' and 'value2' are required.");
    echo json_encode($response);
    exit();
}

$mysqli = new mysqli("localhost", "...", "...", "...");

// check connection 

if ($mysqli->connect_errno) {
    http_response_code(500);
    $response = array("success" => false, "message" => $mysqli->connect_error, "sqlerrno" => $mysqli->connect_errno);
    echo json_encode($response);
    exit();
}

// perform the SELECT

$sql = "SELECT EXISTS(SELECT id, name FROM nametable WHERE id=? AND name=?);";

$stmt = $mysqli->prepare($sql);
if (!$stmt) {
    http_response_code(500);
    $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate);
    echo json_encode($response);
    $mysqli->close();
    exit();
}

if (!$stmt->bind_param("ss", $value1, $value2)) {
    http_response_code(500);
    $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate);
    echo json_encode($response);
    $mysqli->close();
    exit();
}

if (!$stmt->execute()) {
    http_response_code(500);
    $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate);
} else {
    $stmt->bind_result($exists);
    $stmt->fetch();
    $response = array("success" => true, "exists" => boolval($exists));
}

$stmt->close();
$mysqli->close();

echo json_encode($response);

?>

我个人确保我的回复是 JSON 字典,这样我就可以解析有意义的错误消息的结果,例如

struct Response: Codable {
    let success: Bool
    let exists: Bool
}

然后使用 responseDecodable 而不是 responseJSON:


func getHistoryCheck(value1: String, value2: String) {
    let parameters = [
        "value1": value1,
        "value2": value2
    ]

    AF.request(url, parameters: parameters)
        .validate()
        .responseDecodable(of: Response.self, decoder: JSONDecoder()) { response in
            switch response.result {
            case .success(let value):
                if value.exists {
                    ...
                } else {
                    ...
                }

            case .failure(let error):
                if let data = response.data, let string = String(data: data, encoding: .utf8) {
                    print(string) // if there is a server error, the JSON (or even HTML, in some cases) contains useful diagnostic info
                }
                print(error)
            }
        }
}