我在将数据发送到我的在线数据库时遇到问题。当我检查数据库时似乎没有任何内容。我对接收到的响应执行了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