2016-08-23 196 views
0

當軟件通過構造函數初始化並且它在軟件的控制檯內顯示結果時,我有一些軟件通過objective-C向我發送JSON數據:JSON數據沒有被插入到mysql數據庫中objective-C

- (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://輸入我的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"; 


?> 
+1

* *從不**自己建立JSON。使用JSON序列化程序,併爲其提供字典或其他複雜對象。這將爲您節省很多未來的麻煩。 – jcaron

回答

0

我想通了,問題是用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); 

?>