【发布时间】:2011-07-06 13:16:39
【问题描述】:
我正在尝试构建一个客观的 C 应用程序,它使用 ASIHTTPRequest 将数据发布到远程数据库。目前,我正在使用 MAMP Server 并且正在努力让它工作。 php 文件在在线运行时有效,但我无法让 iphone 应用程序将数据发布到 php 文件。这是我的代码:
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
主要
#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");
}
?>
现在我知道更改 main 方法是不好的做法,但我只是想建立一个快速而肮脏的 iphone/php 虚拟连接以使其正常工作,而 main 方法是最简单的选择。当然在真正的应用中,我会使用一个视图来触发这样的动作……
我的代码编译并且没有错误,iOSSimulator 加载..但没有任何内容发布到我的数据库...
编辑:
对不起,我确实添加了,但我复制了旧版本。即使使用异步请求,它仍然不起作用,下面是 postToDB 函数的当前版本:
@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"];
[request startAsynchronous];
}
@结束
【问题讨论】:
-
你有没有考虑过使用 main 是问题的原因?您正在尝试处理所有数据,但尚未调用 UIApplicationMain。你确定所有的数据连接都设置好了?也许您应该只创建一个带有按钮的视图并“正确”测试它
标签: php iphone objective-c xcode asihttprequest