将CodeIgniter发布数据传递给函数

时间:2013-02-14 00:13:04

标签: php codeigniter post

基本上我希望我的多部分表单的控制器有一个功能,可以将后期数据提供给其他功能,如预览和编辑。

功能如下:

function get_post_data()
{
  $post_data_array = array();
  // declaration of all form field names
  $variable_array = array('form_field_1', 'form_field_2', ... 'form_field_n');

  for ($i = 0; $i < count($variable_array); $i++) {
    $variable_value = $this->input->post($variable_array[$i]);
    // turn them into an easy-to-use array
    $post_data_array[$variable_array[$i]] = $variable_value;
  }
  return $post_data_array;
}

这样函数就可以访问它:

function show_preview_form()
{
  $this->load->view('preview_form_view', $this->get_post_data() );
}

function send_to_database()
{
  $data_array = $this->get_post_data();
  $this->Model->insert_to_database($data_array['form_field_1'], ...);
}

目前它不起作用。 Firebug返回500 Internal Status Error状态。你们知道如何解决这个问题吗?

我真的不想在每个需要它的函数中重复长get_post_data

3 个答案:

答案 0 :(得分:1)

你为什么这样做?

您可以使用..

将数据作为数组获取
$post_data = $this->input->post();

...

http://ellislab.com/codeigniter/user-guide/libraries/input.html

答案 1 :(得分:0)

您需要先为$post_data_array分配一个空数组,然后才能为其添加值。

get_post_data函数的开头添加$post_data_array = array();

更新

get_post_data更改为_get_post_data可能也是一个好主意,因为它无法直接从网址访问。 http://ellislab.com/codeigniter/user-guide/general/controllers.html#private

答案 2 :(得分:0)

是的,只需使用

即可
               $this->input->post(); 

获取输入字段发布数据。 此外,您可以通过set_rules检查输入发布字段为

                     $this->form_validation->set_rules('userName','Username','trim|regex_match[/^[a-z,0-9,A-Z_ ]{5,35}$/]|required|xss_clean');
    $this->form_validation->set_rules('userFirstName', 'First name','trim|regex_match[/^[a-z,0-9,A-Z_ ]{5,35}$/]|required|xss_clean');
    $this->form_validation->set_rules('userLastName', 'Last name','trim|regex_match[/^[a-z,0-9,A-Z_ ]{5,35}$/]|required|xss_clean');
    $this->form_validation->set_rules('userEmail', 'Email', 'trim|regex_match[/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/]|required|xss_clean');
    $this->form_validation->set_rules('userPass', 'Password', 'trim|regex_match[/^[a-z,0-9,A-Z]{5,35}$/]|required|xss_clean|md5|callback_check_database');
    if ($this->form_validation->run() == FALSE) {
        //your view to show if validation is false
    } else {
         $user_name = $this->input->post('userName');
        $userfname = $this->input->post('userFirstName');
        $userlname = $this->input->post('userLastName');
        $useremail = $this->input->post('userEmail');
        $userpass = $this->input->post('userPass');
        }