如何从iphone应用程序向服务器发送数据

时间:2012-08-04 04:02:54

标签: php iphone mysql xcode

我正在使用php从iphone应用程序向服务器发送数据,但是当我发布数据时,数据没有插入到数据库中,而它只是在回显中发送[]。

我的iPhone代码

    -(void)submitSurveyAnswers{


     NSString*survey_question_response_id="1";
     NSString*survey_id=@"1";
     NSString *question_id =@"1";
     NSString *survey_response_answer_id =@"1";
     NSString *post =[[NSString alloc] initWithFormat:@"survey_question_response_id=%@&survey_id=%@&question_id=%@&survey_response_answer_id=%@",survey_question_response_id,survey_id,question_id,survey_response_answer_id];
     NSLog(post);
    NSURL *url=[NSURL URLWithString:@"http://myserver-solutions.com/app/surveyAnswer.php?"];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData];
   NSError *error;
   NSURLResponse *response;
   NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

  NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
  NSLog(@"%@",data);
  }

这是我的PHP代码

    <?php
    $host = ""; 
    $user = ""; 
    $pass = ""; 
    $database = ""; 

    $linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host."); 

    mysql_select_db($database, $linkID) or die("Could not find database."); 

    $survey_question_response_id=$_POST['survey_question_response_id'];
    $survey_id=$_POST['survey_id'];
    $question_id=$_POST['question_id'];
    $survey_response_answer_id=$_POST['survey_response_answer_id'];
    echo($survey_question_response_id);

    $query=("INSERT INTO survey_question_responses 

(survey_question_response_id,survey_id,question_id,survey_response_answer_id)

    VALUES ('$survey_question_response_id', '$survey_id','$question_id','$survey_response_answer_id')");

     mysql_query($query,$con);
     printf("Records inserted: %d\n", mysql_affected_rows());
     echo($survey_id)
     ?>

1 个答案:

答案 0 :(得分:0)

我在Github上有一个完整的例子来动态创建表单并将它们提交给POST服务器。您可以根据表单的复杂程度使用它。每个表格都用plist描述,非常有活力。

如果缺少对任何所需表单类型的支持(复选框,下拉列表等),请告诉我,我很乐意添加它们。 (到目前为止,我只在表单中需要基于文本的输入,但如果有需求,我也想将它扩展为更复杂的项目!)

(还包括一个PHP文件来捕获响应。)

https://github.com/mikecheckDev/MDContactForm