0

尝试通过 php 脚本将 JSON 数据从 iOS 应用程序发送到 mysql 数据库时遇到一些问题。

这是iOS应用程序的代码:

- (IBAction)sendButton:(id)sender
{
NSString *currentDate = [[NSString alloc] initWithString:[self getDate]];
NSDictionary *newsData = [[NSDictionary alloc] initWithObjectsAndKeys:titleField.text, @"title", nyheterTextField.text, @"newsText", currentDate, @"date", nil];
NSError *error = [[NSError alloc] init];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newsData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(jsonString);
titleField.text = @"";
nyheterTextField.text = @"";
NSString *urlString = [NSString stringWithFormat:@"http://affectproductions.net/nyheter/upload.php"];

NSMutableData *body = [NSMutableData data];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"json\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@",jsonString] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
    self.recievedData = [NSMutableData data];
    NSLog(@"det funkade");
} else {
    NSLog(@"NSURLConnection failed");
}

这是php脚本:

<html>
<body>

<?php
$json = $_POST["json"];
$con = mysql_connect("xxx", "xxx", "xxx");

mysql_select_db("FreeSir_MarinaLaroverket") or die("Unable to select database");

$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {

mysql_query("INSERT INTO Nyheter (Title, News, Date) VALUES ($value->newsText, $value->title, $value->date)") or die ("error" . mysql_error());
echo "finito";
mysql_close($con);
?>

</body>
</html>

在我将它连接到我的 iOS 应用程序之前,该脚本正在运行,但现在 mysql 数据库中根本没有任何值出现。

此致

自由宁静

4

1 回答 1

0

尝试以下方法,而不是:

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];

NSString *contentType = @"application/json";
于 2013-01-09T19:59:54.987 回答