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";
?>
* *從不**自己建立JSON。使用JSON序列化程序,併爲其提供字典或其他複雜對象。這將爲您節省很多未來的麻煩。 – jcaron