我在將數據發送到我的在線數據庫時遇到問題。當我檢查數據庫時似乎沒有任何內容。我對接收到的響應執行了NSLog,並且它是空白的。如何使用objective-c發佈JSON數據到PHP數據庫?
這裏是.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);
?>
但是,如果我硬編碼的$迴應是一些字符串值,的NSLog接收到的響應,它接收相應的字符串值。
這裏是我的代碼:
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,這就是爲什麼它不張貼,或其他一些問題?
感謝您的協助。
感謝羅布,PHP已被改爲更安全。一個問題:如果我想包含數值,可以說數組中的字段值「緯度」作爲響應的一部分,我該怎麼做?現在,我正在做類似$ response = array(「success」=> false,「message」=> $ mysqli-> error,「latitude」=> $ latitude,...);但是當我在Xcode中獲取json時,即使我的表中有一個緯度值,緯度值也是null。謝謝 – Pangu
是的,構建'$ response'的方式看起來不錯,所以我懷疑在'$ latitude'變量中存在一些錯誤。我會建議發佈一個新的問題,其中包含修訂後的PHP的詳細信息... – Rob