Using NSURLRequest to pass key-value pairs to PHP script with POST
- by Ralf Mclaren
Hi,
I'm fairly new to objective-c, and am looking to pass a number of key-value pairs to a PHP script using POST. I'm using the following code but the data just doesn't seem to be getting posted through. I tried sending stuff through using NSData as well, but neither seem to be working.
NSDictionary* data = [NSDictionary dictionaryWithObjectsAndKeys:
@"bob", @"sender",
@"aaron", @"rcpt",
@"hi there", @"message",
nil];
NSURL *url = [NSURL URLWithString:@"http://myserver.com/script.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[NSData dataWithBytes:data length:[data count]]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"responseData: %@", content);
This is getting sent to this simple script to perform a db insert:
<?php $sender = $_POST['sender'];
$rcpt = $_POST['rcpt'];
$message = $_POST['message'];
//script variables
include ("vars.php");
$con = mysql_connect($host, $user, $pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
mysql_query("INSERT INTO php_test (SENDER, RCPT, MESSAGE)
VALUES ($sender, $rcpt, $message)");
echo "complete"
?>
Any ideas?