尝试通过 php 使用 POST 请求将数据从 Swift 插入 MySQLi 数据库

Trying to insert data from Swift into a MySQLi database using POST request via php

作为序言,我目前仍在学习 Swift 并且只是想尝试尝试从我的应用程序中将数据发送到某种后端。 不确定是否重要,但如果重要:

根据我收集到的信息(请说如果我有这个倒退),数据库上的执行写在 SQL 中,我已将其包含在我的应用程序的获取请求中(工作成功) . PHP 文件充当桥梁,打开数据库与我端之间的连接。

我已经尝试(半成功)3 天在 swift 中编写一个 POST 请求,该请求将从我的应用程序发送数据并将其插入我的数据库。当我说半成功时,我的意思是当从应用程序触发我的 swift 代码中的惰性方法时,数据确实被插入到数据库中,但它是 nil-coalescing 运算符的替代端的数据并且不是我的数据。这让我相信我的 .PHP 文件(几乎)一切正常,并且我的 swift 代码有问题,或者我没有在数据库本身?

具有 table 名为“Students”的数据库 - 包含 5 个字段:

swift - 我要插入数据库的内容:

swift代码:

func postRequest(id: Int, firstName: String, lastName: String, subject: String, grade: Int, completion: @escaping (Error?) -> ()) {
    let insertGradesURL = URL(string: "http://kysodev.com/classroomGrades/insertClassroomGrades.php")!
    var urlRequest = URLRequest(url: insertGradesURL)
    urlRequest.httpMethod = "POST"
    
    let postString = "id=\(id)&firstName=\(firstName)&lastName=\(lastName)&subject=\(subject)&grade=\(grade)"
    urlRequest.httpBody = postString.data(using: .utf8)
    
    let task = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        if error != nil {
            print("error = \(error)")
            return
        }
        print("response - \(response)")
        let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("response string - \(responseString)")
    }
    task.resume()
    
}

我没有从中返回任何错误,但调试器中的响应是:

response - Optional(<NSHTTPURLResponse: 0x280526f80> { URL: http://kysodev.com/classroomGrades/insertClassroomGrades.php } { Status Code: 200, Headers {
Connection =     (
    "Upgrade, Keep-Alive"
);
"Content-Encoding" =     (
    gzip
);
"Content-Type" =     (
    "text/html; charset=UTF-8"
);
Date =     (
    "Mon, 15 Mar 2021 16:37:33 GMT"
);
"Keep-Alive" =     (
    "timeout=5, max=100"
);
Server =     (
    Apache
);
"Transfer-Encoding" =     (
    Identity
);
Upgrade =     (
    "h2,h2c"
);
Vary =     (
    "Accept-Encoding"
);
"X-Powered-By" =     (
    "PHP/7.2.34"
);

} })

insertClassroomGrades.php 文件:

    <?php
$connection=mysqli_connect("localhost","knockyou_seb","*******","knockyou_classroomGrades");

if ($connection->connect_error) {
    error_log ("not connected to db");
  die("Connection failed: " . $conn->connect_error);
} else {
    
    $id = $_POST['id'] ?? 13;
    $firstName = $_POST['firstName'] ?? 'Test';
    $lastName = $_POST['lastName'] ?? 'McTest';
    $subject = $_POST['subject'] ?? 'Test Subject'; 
    $grade = $_POST['grade'] ?? 5;
    
    $sql = "INSERT INTO Students (id, first_name, last_name, subject, grade) VALUES ('".$id."','".$firstName."','".$lastName."','".$subject."','".$grade."');";
}

mysqli_close($connection);
?>

php 以前允许我用示例学生 Test McTest 更新数据库,可惜现在也不起作用了,我不确定是否遇到某种超时问题如果是的话,如何解决这个问题,或者如果是我的 swift 代码,或者只是一切的混合!

我已确保不会向数据库提交重复的 id 字段值,因为我已将该字段设置为唯一。我也尝试改变我的 swift 代码,以便它发送 postString 作为字符串值,但这也没有解决它。

如果有人能指出正确的方向,我将不胜感激,谢谢。

您没有在 PHP 代码中执行查询,请尝试像这样编辑您的代码:

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connection = new mysqli("localhost", "knockyou_seb", "*******", "knockyou_classroomGrades");

$id = $_POST['id'] ?? 13;
$firstName = $_POST['firstName'] ?? 'Test';
$lastName = $_POST['lastName'] ?? 'McTest';
$subject = $_POST['subject'] ?? 'Test Subject';
$grade = $_POST['grade'] ?? 5;

$sql = $connection->prepare("INSERT INTO Students (id, first_name, last_name, subject, grade) VALUES (?, ?, ?, ?, ?)");
$sql->bind_param("isssi", $id, $firstName, $lastName, $subject, $grade);
$sql->execute();
$sql->close();

$connection->close();

两点注意事项:

  1. 在 Swift 中构建 application/x-www-form-urlencoded 请求时,您必须对值进行百分比编码。例如。 。如果您发送带有未转义保留字符的 post 请求(例如,如果“主题”中有 space),它将失败。

  2. 不要只将值插入 SQL 语句。您应该将值绑定到 ? 占位符。参见 。如果插入一个带有 ' 字符的值,您的服务器代码将失败。另外,您正在向 SQL 注入攻击开放自己。