Alessandro Pirovano
Alessandro Pirovano

Reputation: 2551

Objective-C send special character POST

I have create a application that send two POST parameter to my file PHP and it's save data in my database.

The code into xcode project that send parameter is:

NSString *post = [[NSString alloc] initWithFormat:@"&key1=%@&key2=%@", myString1, myString2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.mysite.com/test.php"]]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

The code into my file PHP that save data into my database is:

$val1 = $_POST['key1'];
$val2 = $_POST['key2'];
$val1 = urldecode($val1);
$val2 = urldecode($val2);

$sql = "INSERT INTO test(nome, cognome) VALUES ('$val1', '$val2')";
mysql_query($sql);

The problem is that if I insert a parameter that contains special character (for example é or ä), my program save into database normal character (e and a).

Can someone help me with this?

Upvotes: 2

Views: 1198

Answers (1)

Caleb
Caleb

Reputation: 125007

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

The problem here is that you're using ASCII, but ASCII doesn't contain é, ä, etc. You should be using Unicode instead. Try switching NSASCIIStringEncoding for NSUTF8StringEncoding in the code above.

Upvotes: 2

Related Questions