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
211 views
in Technique[技术] by (71.8m points)

ios - How to post JSON data to PHP database using objective-c?

I'm having an issue sending data to my online database. Nothing seems to post when I check the database. I performed an NSLog on the received response, and it's blank.

Here is the .php:

<?php
        $db_host="someurl.com";
        $db_username="some_user"; 
        $db_pass="some_passwd";
        $db_name="some_db";

        $conn = mysql_connect($db_host, $db_username, $db_pass) or die ("Could not connect to 
                                                                        MySQL"); 

        mysql_select_db("$db_name") or die ("No database");

        // array for JSON response
        $json = $_SERVER['HTTP_JSON'];
        $data = json_decode($json);
        $some1_id = $data->some1_id;
        $imei = $data->imei;

        //does the imei exist?
        $result = mysql_query("SELECT * FROM usr_go WHERE imei = '".$imei."'"); 

        if (mysql_num_rows($result) == 0){
            if(isset($some1_id))
                $result = mysql_query("INSERT INTO usr_go(some1_id, imei) VALUES('".$some1_id."','".$imei."')");
        }
        else{
            if(isset($some1_id))
                $result = mysql_query("UPDATE usr_go SET some1_id = '".$some1_id."' WHERE imei = '". $imei ." AND some1_id IS NULL ");
        }

        mysql_close($conn);

        header('Content-type: application/json');
        $response = $result;
        echo json_encode($response);
?>

However, if I hard-code the $response to be some string value, and NSLog the received response, it receives the appropriate string value.

Here is my code:

NSDictionary *dict = @{@"some1_id" : [NSNumber numberWithInt:self.cellIndex]};

    NSError *error = nil;

    NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];

    if (json)
    {
        NSURL *url = [NSURL URLWithString:@"someurl.com"];

        NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
        [req setHTTPMethod:@"POST"];
        [req setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
        [req setHTTPBody:json];

        NSURLResponse *res = nil;
        NSData *ret = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&error];

        NSString *resString = [[NSString alloc] initWithData:ret encoding:NSUTF8StringEncoding];
        NSLog(@"response String: %@",resString);


        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON Output: %@", jsonString);
    }
    else
    {
        NSLog(@"Unable to serialize the data %@: %@", dictionary, error);
    }

Is it the fact that it's not possible to insert the IMEI, which is why it's not posting, or some other issue?

Thanks for your assistance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

A couple of observations:

  1. You should use msqli interface rather than the deprecated mysql interface.

  2. You should never take input and just use it in SQL statement. Either use mysqli_real_escape_string or bind values (as shown below). This is critical to ensure you aren't susceptible to SQL injection attacks. It also protects you against innocent errors that can arise if the inserted value just happens to contain a reserved character.

  3. Rather than trying to just json_encode the result of mysqli_query result, you should build a more meaningful associative array. For example, you might check the result of the mysqli call and return one JSON if it was successful, and another on failure. I might suggest having the failure rendition return the error message.

  4. You should test your PHP either in a web browser, or test it from a device using something like Charles. Make sure you're getting back the JSON you expected before you go too far with your client code. Bottom line, see if you can test the client code and the server code in isolation of each other (or keeping it as simple as possible at first).

  5. I'm not familiar with this $_SERVER['HTTP_JSON']; construct. If that works for you, great, but it doesn't work on my server. I've historically done fopen of php://input as illustrated below.

For example, this is a different database/table, but it might illustrate the idea of what the PHP code might look like:

// read JSON input

$handle = fopen("php://input", "rb");
$raw_post_data = '';
while (!feof($handle)) {
    $raw_post_data .= fread($handle, 8192);
}
fclose($handle);

$request_data = json_decode($raw_post_data, true);

// prepare header for reply

header("Content-Type: application/json");

// open database

$mysqli = new mysqli($host, $userid, $password, $database);

// check connection 

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

// perform the insert

$sql = "INSERT INTO locations (message, device, longitude, latitude) VALUES (?, ?, ?, ?)";

if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param("ssdd", $request_data["message"], $request_data["device"], $request_data["latitude"], $request_data["longitude"]);

    if (!$stmt->execute())
        $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate);
    else
        $response = array("success" => true);

    $stmt->close();
} else {
    $response = array("success" => false, "message" => $mysqli->error, "sqlerrno" => $mysqli->errno, "sqlstate" => $mysqli->sqlstate);
}

$mysqli->close();

echo json_encode($response);

Obviously, change this for your tables, but it illustrates some of the above concepts. I would generally add more error checking (e.g. the Content-Type of the request, test to make sure variables were set before I tried to use them, etc.), but you probably get the idea.


On the client side, there are also a few more minor observations:

  1. The most serious problem is the use of sendSynchronousRequest. Use sendAsynchronousRequest instead (or any of a myriad of other, asynchronous techniques). Never issue synchronous requests from the main thread.

  2. When parsing the response, resString will contain the raw JSON. I don't know what the jsonData variable you reference when building jsonString, but that doesn't look right.

    If you want to parse the response, it would be:

    NSError *parseError;
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    

    By the way, the above assumes you return a JSON dictionary in your response, like I do in my example, rather than what your original JSON did.


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

...