Background
Using Codeigniter
with form_helper
and form_validation
to do some form processing. Form has been validated successfully in the controller
.
Now we need to put this data into the database using the model
class.
Assumptions
Lets assume our form has several input elements (e.g. >20).
Question
Which of the following code snippets will be more efficient? Both snippets are obviously inside the controller method to which the form submits data.
Code Snippet 1
if ($this->form_validation->run())
{
// validation successful, now collect the values in a variable to pass it to the model.
$form_data['field1'] = $this->form_validation->set_value('field1');
$form_data['field2'] = $this->form_validation->set_value('field2');
// AND SO ON
$form_data['fieldN'] = $this->form_validation->set_value('fieldN');
// Now put this data into database.
$this->corresponding_model->write_to_db($form_data);
}
Code Snippet 2
if ($this->form_validation->run())
{
// validation successful, now collect the values in a variable to pass it to the model.
$form_data['field1'] = $this->input->post('field1');
$form_data['field2'] = $this->input->post('field2');
// AND SO ON
$form_data['fieldN'] = $this->input->post('fieldN');
// Now put this data into database.
$this->corresponding_model->write_to_db($form_data);
}
So essentially what I am asking is: What is better to get the post data for some arbitrary form element? $this->input->post
or $this->form_validation->set_value()
?
PS: If we look the the set_value()
and post()
functions in the code (please see below), obviously set_value()
is going to be faster as post()
loops through the entire $_POST
. So in a sense it is also about what is the best practice?
Form_validation.php, set_value() method
public function set_value($field = '', $default = '')
{
if ( ! isset($this->_field_data[$field]))
{
return $default;
}
// If the data is an array output them one at a time.
// E.g: form_input('name[]', set_value('name[]');
if (is_array($this->_field_data[$field]['postdata']))
{
return array_shift($this->_field_data[$field]['postdata']);
}
return $this->_field_data[$field]['postdata'];
}
Input.php, post() method
function post($index = NULL, $xss_clean = FALSE)
{
// Check if a field has been provided
if ($index === NULL AND ! empty($_POST))
{
$post = array();
// Loop through the full _POST array and return it
foreach (array_keys($_POST) as $key)
{
$post[$key] = $this->_fetch_from_array($_POST, $key, $xss_clean);
}
return $post;
}
return $this->_fetch_from_array($_POST, $index, $xss_clean);
}