Swift 不插入到 MySQL 数据库的 httppost 数据

标签: json MySQL PHP Swift
发布时间: 2017/3/5 16:53:02
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我想将数据发送到 php 并将它插入到 mysql 数据库,但这似乎并不工作。我已经尝试将数据发送到 php 只是为了将其编码到 json 和回声回 swift ,它返回一个结果,所以这意味着 php 文件收到的数据。然而不工作插入数据。

swift2 httppost

func post() {

    let myUrl = NSURL(string: "http://localhost:8080/json/json.php");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST"
    // Compose a query string
    let postString = "firstName=James&lastName=Bond";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")

        //Let’s convert response sent from a server side script to a NSDictionary object:

        do{

            let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary

            if let parseJSON = myJSON {
                // Now we can access value of First Name by its key
                let firstNameValue = parseJSON["firstName"] as? String
                print("firstNameValue: \(firstNameValue)")
            }


        }catch let error as NSError {
            print("JSON Error: \(error.localizedDescription)")
        }

    }

    task.resume()

}

json.php

<?php
// Read request parameters
$firstName= $_REQUEST["firstName"];
$lastName = $_REQUEST["lastName"];// Store values in an array

$conn = mysqli("localhost", "root", "root", "notify");

$query = mysqli_query($conn, "INSERT INTO user values('', '$firstName',   
'$lastName')");

 ?>

解决方法 1:

如果有服务器只是回显请求的工作原理,然后这个问题取决于在服务器上,不是客户端代码。我建议将添加一些错误处理在 PHP 代码中︰

<?php

// specify that this will return JSON

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

// open database

$con = mysqli_connect("localhost","user","password","notify");

// Check connection

if (mysqli_connect_errno()) {
    echo json_encode(array("success" => false, "message" => mysqli_connect_error(), "sqlerrno" => mysqli_connect_errno()));
    exit;
}

// get the parameters

$field1 = mysqli_real_escape_string($con, $_REQUEST["firstName"]);
$field2 = mysqli_real_escape_string($con, $_REQUEST["lastName"]);

// perform the insert

$sql = "INSERT INTO user (first_name, last_name) VALUES ('{$field1}', '{$field2}')";

if (!mysqli_query($con, $sql)) {
    $response = array("success" => false, "message" => mysqli_error($con), "sqlerrno" => mysqli_errno($con), "sqlstate" => mysqli_sqlstate($con));
} else {
    $response = array("success" => true);
}

echo json_encode($response);

mysqli_close($con);

?>

备注︰

  1. 我不会推荐作为登录 root

  2. 请确保您使用 mysqli_real_escape_string 来保护自己免受 SQL 注入攻击 (见第 1 点)。

  3. 不知道你 user 表有其他字段,但如果是这样,你可能想要指定列名在 insert 语句。即使你只有这两列,它是"面向未来"的良好习惯您的代码。

  4. 请注意,我已经改变了这一点,生成 JSON 响应。我这样做,是因为它更容易为客户端代码来解析和处理的响应。我会离开 NSJSONSerialization 给你。

赞助商