2013-12-08 174 views
1

我使用此方法发送post请求到我的服务器并将数据保存到sql数据库 但我有一个问题,我错过了一些字符时,数据保存到数据库 例如我有这个字符串“例如交++请求++” 通过缺失+加号收到数据库字符串修改 “例如POST请求” 当 这里是我的代码发送http发布请求时发生错误

的Xcode

NSString *STR = @"mystring=example post ++ request ++"; 
NSData *PostData = [STR dataUsingEncoding:NSUTF8StringEncoding]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://MySiteUrl.com/example.php"]]; 

    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"]; 
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request setHTTPBody:PostData]; 
    [request setHTTPMethod:@"POST"]; 

    NSError *error = nil; 
    NSURLResponse *response = nil; 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 

PHP代码

$STR = $_POST['mystring']; 

      header ('Content-Type: text/html; charset=UTF-8'); 
$con = mysql_connect("localhost","xxxxxx","xxxx"); 
      mysql_select_db("xxxxxxx", $con); 
      mysql_query("SET NAMES utf8"); 

$STR = trim($STR); 

mysql_query("INSERT INTO `xxxxxxx`.`table` (`id`, `mystring`) VALUES (NULL, '$STR');"); 
+1

**警告:**您正在使用[a **弃用的**数据库API](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql -phunctions-in-php)并且应该使用[现代替换](http://php.net/manual/en/mysqlinfo.api.choosing.php)。你也**易受[SQL注入攻击](http://bobby-tables.com)**,现代的API会更容易[防守](http://stackoverflow.com/questions/60174/)我怎么可以防止SQL注入在PHP)自己从。 –

回答

1

请记住+,在一个URL中,意味着一个空格。如果你想传递一个+符号,那么你必须对它进行编码,我认为你的xcode是通过UTF8格式来完成的。在POST中,请求参数作为请求正文中的查询字符串。因此,调试您的PHP代码,并确保一旦您的PHP收到该数据,然后仍然保持UTF8。如果不是,那么只需在php中使用urlencode(string $ str)将其转换。我认为你的问题是编码,你需要调试你的代码,以确定哪个部分没有正确编码。好问题和好运