Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

php - Swift httppost data not inserting to MySQL database

I am trying to send data to php and insert it to mysql database but it doesn't seem to work. I have tried sending data to php just to encode it to json and echo it back to swift and it returns a result so it means that the php file received the data. However inserting the data is not working.

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')");

 ?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If having the server just echo the request works, then the problem rests within the server, not the client code. I would suggest adding some error handling in the PHP code:

<?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);

?>

Notes:

  1. I wouldn't recommend logging in as root.

  2. Make sure you use mysqli_real_escape_string to protect yourself against SQL injection attacks (see point 1).

  3. I don't know if your user table has other fields in it, but if so, you might want to specify the column names in the insert statement. Even if you only have those two columns, it's a good way to "future-proof" your code.

  4. Note, I've changed this to generate JSON response. I do that because it makes it easier for the client code to parse and handle the response. I'll leave the NSJSONSerialization to you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...