Insert data from an array into the database by CodeIgniter

1

I am trying to make a INSERT using CodeIgniter and would like to know if there is a more practical form than the one used below:

MODEL

public function set_cliente() {     

    $dados = array(
        'codigo_cliente' => $this->input->post('cCodigocliente'),
        'data_cadastro' => $this->input->post('cDatacadastro'),
        'hora_cadastro' => $this->input->post('cHoracadastro'),
        'funcionario' => $this->input->post('cFuncionario'),
        'empresa' => $this->input->post('cEmpresa'),
        'representante' => $this->input->post('cRepresentante'),
        'modalidade' => $this->input->post('cModalidade')
    );   
    $this->db->insert('tb_clientes', $dados);

}

Would you have some way to do it without typing all the fields?

    
asked by anonymous 27.09.2017 / 20:58

1 answer

0

You can automate part of the process with code generation by mapping the form field names to the table fields. In the model you can define an attribute called $campos it is an array where your keys are the form field names and the values the column names.

When calling $this->input->get/post() passing null as first argument and true as the second all form fields are returned in an associative array.

In the example I left $campos as the method's local variable

public function set_cliente() {   
  $campos = array('id' => 'codigo', 'nome' => 'nm', 'email' => 'ml', 'idade' => 'dd');
  $valores = $this->input->get(null, true);
  $dados = array();
  foreach($valores as $k => $v){
    if(isset($campos[$k])){
        $nomeTabela = $campos[$k];
        $dados[$nomeTabela] = $v;
    }  
  }
  $this->db->insert('tb_clientes', $dados);
}

Documentation:

CI input class

    
27.09.2017 / 21:32