【问题标题】:JSON data not being inserted into mysql database from objective-CJSON数据没有从Objective-C插入到mysql数据库中
【发布时间】:2016-12-30 20:37:28
【问题描述】:

当软件通过构造函数初始化并在软件控制台内显示结果时,我有一些软件通过 Objective-C 向我发送 JSON 数据:

- (id)initWithAPIManager:(id)apiManager
{
_apiManager = apiManager;

NSString *strURL = @"http://mysite/DBTest.php";
NSLog(@"URL:\t%@", strURL );
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if ( request != nil ) {
    NSString *jsonData = [NSString stringWithFormat:@"{\"IP\":\"%@\",\"Date\":\"%@\"}",
                          [self GetIP],
                          [self GetDate]];

    NSData *requestData = [NSData dataWithBytes:[jsonData UTF8String]
                                         length:[jsonData lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:requestData];
    NSLog(@"will create connection");

    // Send a synchronous request
    NSURLResponse * response = nil;
    NSError * NSURLRequestError = nil;
    //- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * __nullable data, NSURLResponse * __nullable response, NSError * __nullable error))
    //[NSURLConnection dataTaskWithRequest:]
    NSData * responseData = [NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&NSURLRequestError];
    if ( responseData != nil ) {
        NSLog(@"responseData is valid.");

        NSString *myString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"myString:\t%@", myString);
    } else {
        NSLog(@"responseData is nil!");
    }
} else { // uh oh
    NSLog( @"Error creating the URL request!" );
}

//NSLog(@"IP address:\t%@", [self getIP] );
OldIPGettingThingy();


return self;
}

当我使用本地 JSON 文件时,我的 PHP 脚本可以正常工作,但是当我切换到使用 php://input 时,我的 var_dump 显示为 NULL,并且我没有任何内容插入到我的数据库中。提前致谢。

<?php


$con = new PDO('mysql:host=localhost;dbname=pirates','root','password');

//$raw_data = file_get_contents('php://input');
$raw_data = file_get_contents('tes.json');

$data = json_decode($raw_data, true);

var_dump($data);

$stmt = $con->prepare("INSERT INTO Tracking values(?,?,?)");

foreach ($data as $row){

    $stmt->bindParam(1, $row['id']);
    $stmt->bindParam(2, $row['IP Address']);
    $stmt->bindParam(3, $row['timestamp']);
    $stmt->execute();

    }

echo "got here";


?>

【问题讨论】:

  • 从不自己构建 JSON。使用 JSON 序列化器,并为其提供字典或其他复杂对象。这将为您将来省去很多麻烦。

标签: php mysql objective-c json


【解决方案1】:

我发现问题出在 Objective-c 代码上,我需要使用字典而不是字符串格式:

- (id)initWithAPIManager:(id)apiManager
{
_apiManager = apiManager;


NSString *strURL = @"http://myip/DBTest.php";
NSLog(@"URL:\t%@", strURL );
NSURL *url = [NSURL URLWithString:strURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if ( request != nil ) {
    NSDictionary *dict = @{ @"IP" : [self GetIP],
                            @"Date" : [self GetDate]};


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

    NSString *jsonData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    NSData *requestData = [NSData dataWithBytes:[jsonData UTF8String]
                                         length:[jsonData lengthOfBytesUsingEncoding:NSASCIIStringEncoding]];

    [request setHTTPMethod:@"POST"];
    //[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:requestData];
    NSLog(@"will create connection");

    // Send a synchronous request
    NSURLResponse * response = nil;
    NSError * NSURLRequestError = nil;

    NSData * responseData = [NSURLConnection sendSynchronousRequest:request
                                                  returningResponse:&response
                                                              error:&NSURLRequestError];
    if ( responseData != nil ) {
        NSLog(@"responseData is valid.");

        NSString *myString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
        NSLog(@"myString:\t%@", myString);
    } else {
        NSLog(@"responseData is nil!");
    }
} else { // uh oh
    NSLog( @"Error creating the URL request!" );
}

return self;
}

还有我的 PHP:

<?php

$host = "localhost";
$userid = "root";
$password ="password";
$database = "database"; 


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

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

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

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

$sql = "INSERT INTO table (IP,Date) VALUES (?,?);";

if ($stmt = $mysqli->prepare($sql)) {
    $stmt->bind_param("ss", $request_data["IP"], $request_data["Date"]);

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

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

$mysqli->close();

echo json_encode($response);

?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2013-05-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    • 2015-05-27
    • 1970-01-01
    相关资源
    最近更新 更多