So I fixed the question codes with the new code that works and also changed the Title of the question for other people to be assist by it.
My problem was that inside the application i’m using in POST method, but on the PHP side, I’m using in GET method. Just changed it to POST and it worked perfectly.
Enjoy.
I keep getting error from my server that the username is wrong, what am I doing wrong here?
Thanks for your help.
- (void)addNewUser:(NSString *)username andDate:(NSDate *)date
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString * urlString = [NSString stringWithFormat:@"http://www.myurl.com/url/insert.php"];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
NSString *strDate = [dateFormatter stringFromDate:date];
NSString *paramDataString = [NSString stringWithFormat:@"username=%@&date=%@",[username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[strDate stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:[paramDataString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *requestData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
}
On the server side I have this: (PHP)
<?php
header("Content-type: text/html; charset=utf8");
$connection = mysql_connect("localhost","myusername","mypassword");
if(!$connection)
{
die("database connection failed:" . mysql_error());
}
$db = mysql_select_db("db_users",$connection);
if(!db)
{
die("database connection failed:" . mysql_error());
}
mysql_query("SET NAMES 'utf8'",$connection);
?>
<?php
$varGet1 = $_POST['username'];
$varGet2 = $_POST['date'];
if (!$varGet1) {
$message = "no username";
} else if (!$varGet2) {
$message = "no date";
} else {
$query = "INSERT INTO `Users` (username, date, first) VALUES('{$varGet1}','{$varGet2}','0')";
$query = mysql_query($query,$connection);
if($query) {
$message = "Added";
} else {
$message = "Error";
}
}
echo($message);
mysql_close($connection);
?>
Nothing is really wrong. You just
GETfrom your php whilePOSTing from objective-c. Switch to$_POSTand you’ll be good to go.