I'm trying to post data from my UITextFields to a MySQL database. The console says my connection is successful, but for some reason the data isn't posting to the database? Any idea as to why? Here's my code:
ViewController.h
-(IBAction)addParty:(id)sender;
@property (strong, nonatomic) IBOutlet UITextField *firstname;
@property (strong, nonatomic) IBOutlet UITextField *lastname;
@property (strong, nonatomic) IBOutlet UITextField *phone;
@property (strong, nonatomic) IBOutlet UITextField *email;
@property (strong, nonatomic) IBOutlet UITextField *guests;
@property (nonatomic, copy) NSDictionary *venueDetail;
@end
ViewController.m
- (IBAction)addParty:(id)sender
{
NSString *strURL = [NSString stringWithFormat:@"guestfirst=%@&guestlast=%@", firstname.text, lastname.text];
NSData *postData = [strURL dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://myurl.com/phpfile.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(@"Connection Successful");
}
else
{
NSLog(@"Connection could not be made");
}
}
Post.php
<?Php
include('connect.php');
if (isset ($_POST["guestfirst"]) && isset ($_POST["guestlast"])){
$guestfirst = $_POST["guestfirst"];
$guestlast = $_POST["guestlast"];
} else {
$guestfirst = "none";
$guestlast = "none";
}
// Insert value into DB
$sql = "INSERT INTO events (guestfirst, guestlast) VALUES ('$guestfirst', '$guestlast');";
$res = mysql_query($sql,$conn) or die(mysql_error());
mysql_close($conn);
if($res) {
$response = array('status' => '1');
} else {
die("Query failed");
}
echo json_encode($res);
exit();
?>