2013-03-15 50 views
0

我试图通过一个php表单发布这4个文本字段,然后将其插入到我的数据库中。UITextField通过PHP发布到MySQL

IBOutlet UITextField *who; 
    IBOutlet UITextField *what; 
    IBOutlet UITextField *where; 
    IBOutlet UITextField *contact; 

而且在Xcode POST方法是:

- (IBAction)post:(id)sender 
{ 
    NSLog(@"%@", who); 
    NSLog(@"%@", what); 
    NSLog(@"%@", where); 
    NSLog(@"%@", contact); 
    // create string contains url address for php file, the file name is post.php, it receives parameter :name 
    NSString *strURL = [NSString stringWithFormat:@"http://website.com/post.php?who=%@&what=%@&where=%@&contact=%@",who, what, where, contact]; 

    // to execute php code 
    NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; 

    // to receive the returend value 
    NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]; 

    NSLog(@"%@", strResult); 
} 

我post.php中文件看起来像这样:

<?php header("Location: feed.php"); ?> 
<?php 

define ('DB_NAME','database_name'); 
define ('DB_USER','user'); 
define ('DB_PASSWORD','root'); 
define ('DB_HOST','localhost'); 

$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); 

if (!link) { 
die('Could not connect: ' .mysql_error()); 
} 

$db_selected = mysql_select_db(DB_NAME, $link); 

if (!$db_selected) { 
die('Can\'t use ' . DB_NAME . ': ' . mysql_error()); 
} 

$value1 = $_REQUEST['who']; 
$value2 = $_REQUEST['what']; 
$value3 = $_REQUEST['where']; 
$value4 = $_REQUEST['contact']; 

$sql = mysql_query("INSERT INTO content VALUES ('','".mysql_real_escape_string($value1)."','".mysql_real_escape_string($value2)."', '".mysql_real_escape_string($value3)."','".mysql_real_escape_string($value4)."')") or die(mysql_error()); 


if (!mysql_query($sql)) { 
die('Error: ' . mysql_error()); 
} 
    echo "You've just posted your text!"; 
mysql_close(); 
?> 

但是当我尝试从应用程序后,没有任何反应...

+0

你为什么试着运行查询两次? $ sql = mysql_query()或die();那么如果(!mysql_query($ sql))< - 不包含sql语句 – Waygood 2013-03-15 12:30:28

回答

1

为什么<?php header("Location: feed.php"); ?>位于代码的顶部?这会将您重定向到另一个页面。

if (!mysql_query($sql)) { 
    die('Error: ' . mysql_error()); 
} 

执行查询的第二时间。做:

if (!$sql) { 
    die('Error: ' . mysql_error()); 
} 

改为。

+0

是的,但这不是问题。在网站上,我在index.php上有这个表单。所以当我填写表单后,它会发布它,然后重定向到feed.php ... – tracifycray 2013-03-15 12:30:05

+0

重定向失去了该帖子。包括( 'feed.php');而不是OR动作=“feed.php”的形式 – Waygood 2013-03-15 12:32:08

+0

重定向将强制浏览器到新的网址,而不是执行其余的代码:http://php.net/manual/en/function.header.php – 2013-03-15 12:34:21