Insert data from an array into the database by Codeigniter

Asked

Viewed 593 times

2

I’m 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 having to type all the fields?

  • The field name in HTML does not match the column name in the database, so you will not be able to make PHP magically know where to store each value, so no, there’s no way to do that. Even if it was, it would not be recommended, because it would be very trusting the data received by the request.

  • But if I use the same name in the fields, it would be possible?

  • 1

    The question is: is there such a need? There are 7 lines of code.

  • The 7 lines were just for example, I have many fields beyond these.

  • What if a field is not sent together? Or if other fields are sent than expected? What should be the behavior of the application?

  • 1

    Your question goes against another question, what I am wanting to do is common, or is done the way I was doing. I would like to know your opinion, even for the security issue, as I questioned earlier.

Show 1 more comment

1 answer

1

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

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

In the example I left $campos as a local variable of the method

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.