ASIHTTPRequest Issue - Cannot POST data to Database
I'm trying to build an objective C app which posts data to a remote database using ASIHTTPRequest. Currently, I am using MAMP Server and am struggling to get it to work. The php file works when run online, but I am having trouble getting the iphone app to post data to the php file. HEre is my code:
dbconnect.h
#import <Foundation/Foundation.h>
@interface dbconnect : NSObject {
}
-(void) postToDB:(NSString*) msg;
@end
dbconnect.m
#import "dbconnect.h"
#import "ASIFormDataRequest.h"
@implementation dbconnect
-(void) postToDB:(NSString*) msg{
NSString *myphp = @"/Applications/MAMP/htdocs/databases/test.php";
NSURL *url = [NSURL URLWithString:myphp];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:msg forKey:@"message"];
}
@end
main
#import <UIKit/UIKit.h>
#import "dbconnect.h"
int main(int argc, char *argv[]) {
dbconnect* dbc;
dbc = [[dbconnect alloc]init];
[dbc postToDB:@"TESTING"];
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
php
<?php
//connect to database
function connect() {
$dbh = mysql_connect ("localhost", "root", "root") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("testers", $dbh);
return $dbh;
}
//store posted data
if(isset($_POST['message'])){
$message = $_POST['message'];
$dbh = connect();
$query = "INSERT INTO messages (message) VALUES ('$message')";
$result = mysql_query( $query ) or die ("didn't query");
}
?>
Now I know it is bad practise to change the main method, but I just wanted to build a quick and dirty iphone/php dummy connection to get it working and the main method was the easiest option. Of course in the real app, I will use a view to trigger such actions...
My code compiles and there are no errors, iOSSimulator loads up..but nothing gets posted to my database...
EDIT:
Sorry I did add that but I copied my old version over. It still doesn't work even when using an asynchronous request, below is the current version of the postToDB function:
@implementation dbconnect
-(void) postToDB:(NSString*) msg{
NSString *myphp开发者_C百科 = @"/Applications/MAMP/htdocs/databases/test.php";
NSURL *url = [NSURL URLWithString:myphp];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:msg forKey:@"message"];
[request startAsynchronous];
}
@end
All else aside, your request is never executed. Make sure to invoke startSynchronous
or startAsynchronous
on the request object. Please consider reading the "How To use it" guide to ASIHTTPRequest.
精彩评论