【发布时间】:2014-04-10 04:06:20
【问题描述】:
我在 PHP 中使用带有 POST 方法的 JSON,我能够在 Xcode 中显示值,但这些值没有显示在 mySql 中。它显示空行。我认为我的 PHP 代码可能缺少某些部分。请帮帮我。
我的 Xcode 代码
- (IBAction)uploadData:(id)sender {
NSDictionary *loginDict = [NSDictionary dictionaryWithObjectsAndKeys:
self.shipmentID.text, @"name",
nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:loginDict
options:0 // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// NSString *jsonString=@"{"username":"root","password":""}";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *post = [NSString stringWithFormat:@"json=%@", jsonString];
//NSLog(@"fweffwr %@" , jsonString);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
[request setURL:[NSURL URLWithString:@"http://localhost/~robot/post.php"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSLog(@"checking %@",post);
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d",[postData length]] forHTTPHeaderField:@"Content-Length"];
// [[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection connectionWithRequest:request delegate:self];
}
}
我的 PHP 代码
<?php
$con=mysqli_connect("127.0.0.1","root","","PalletApp");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Success";
}
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
echo "\n\n";
$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
echo "\n\n";
$name = $data->name;
echo "Result: \n";
echo "--------------\n";
echo "Name : ".$name;
$sql = "INSERT INTO sample values('$name')";
mysqli_query($con,$sql);
mysqli_close($con);
?>
【问题讨论】:
-
sample表中的字段是什么,可能您正在尝试将数据输入错误的字段 -
你有没有试过回显
$name看看有没有价值? -
示例数据库中只有一个字段,如果我们给出 echo ,我会不知道它会显示在哪里。如果我们对 $name 的值进行硬编码,它就可以正常工作。
-
var_dump($json)打印什么? -
我是 PHP 新手,不知道 PHP 回显值打印在哪里。