I have an iPhone application where I'd like to send some form data to my site (which is written in PHP).
//This problem has now been solved. Typo in url.. :(
NSString *urlString = "http://www.mywebsite.com/test.php";
NSUrl *url = [NSURLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *variableToSend = [NSString stringWithFormat:@"name=John"];
//I have assumed that where I write "name=John" that "name" is in Php equal
//to $_POST['name']?, and that "John" is the value of it?
[request setHTTPMethod:@"POST"];
//I don't quite understand these..
[request setValue:[NSString stringWithFormat:@"%d", [variableToSend length]] forHTTPHeaderField:@"Content-length"];
[request setHTTPBody:[variableToSend dataUsingEncoding:NSUTF8StringEncoding]];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
My php-file just does $name = $_POST['name']; and writes $name to a database. I created a < form > with method="post", action="", with a textField with the name "name", and that worked. That value was sent to the database.
I have seen this code-example in many answers around, but it doen's work for me.. Some of the code-lines I don't understand, so I believe there is something wrong with how I set up the php vs how the code is sending the variable.. Anyone knows where I went wrong?
(The code is written by hand here now, so there might be typos, but everything compiles in xcode, and if I NSLog(@"%@", request), I get "< NSURLConnection: 0x1d342c24>" or something.. Don't know if this is correct..)
EDIT
My test.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$connection = mysql_connect("host","un","pw");
if (!$connection){
die('Error: ' . mysql_error());
}
if(isset($_POST['name']))
{
$name = $_POST['name'];
mysql_select_db("db", $connection);
mysql_query("INSERT INTO tablename(Name)
VALUES ('$name')");
mysql_close($connection);
}
?>
</body>
</html>
Sti