如何使用Objective-C将JSON数据发布到PHP数据库? [英] How to post JSON data to PHP database using objective-c?

查看:85
本文介绍了如何使用Objective-C将JSON数据发布到PHP数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将数据发送到在线数据库时出现问题.当我检查数据库时,似乎什么都没有发布.我对收到的响应执行了NSLog,它为空.

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.

这是.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);
?>

但是,如果我将$ response硬编码为某个字符串值,然后NSLog接收到的响应,它将接收适当的字符串值.

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

这是我的代码:

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

是否确实无法插入IMEI(这就是为什么它不发布)或其他问题的事实?

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

感谢您的帮助.

推荐答案

一些观察结果:

  1. 您应该使用 msqli 接口,而不要使用不推荐使用的接口mysql界面.

永远不要接受输入,而只能在SQL语句中使用它.使用 mysqli_real_escape_string 或绑定值(如下所示) .这对于确保您不受SQL注入攻击的影响至关重要.如果插入的值恰好包含保留字符,它还可以防止出现无辜的错误.

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.

您应该构建一个更有意义的关联数组,而不是尝试仅将json_encode结果作为mysqli_query结果.例如,您可以检查mysqli调用的结果,如果成功,则返回一个JSON,失败时返回另一个.我可能建议让故障再现返回错误消息.

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.

您应该在网络浏览器中测试PHP,或者使用查尔斯之类的设备对PHP进行测试. .在处理客户端代码之前,请确保已取回期望的JSON.最重要的是,看看是否可以彼此隔离地测试客户端代码和服务器代码(或首先使其尽可能简单).

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).

我对这个$_SERVER['HTTP_JSON'];构造不熟悉.如果这对您有用,那很好,但是在我的服务器上不起作用.历史上,我已经完成了php://inputfopen,如下所示.

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.

例如,这是一个不同的数据库/表,但是它可能说明了PHP代码可能是什么样的想法:

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

显然,为您的表更改此设置,但它说明了上述一些概念.我通常会添加更多错误检查(例如,请求的Content-Type,在尝试使用变量之前进行测试以确保已设置变量等),但是您可能会明白.

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. 最严重的问题是使用sendSynchronousRequest.请改用sendAsynchronousRequest(或无数其他异步技术).永远不要从主线程发出同步请求.

  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.

在解析响应时,resString将包含原始JSON.我不知道在构建jsonString时要引用什么jsonData变量,但这看起来并不正确.

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];

顺便说一句,以上假设您在响应中返回了JSON字典,就像我在示例中所做的那样,而不是原始JSON所做的事情.

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.

这篇关于如何使用Objective-C将JSON数据发布到PHP数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆