Use of loop in codeigniter

0

Hello, how are you?

I'm having a big problem in codeigniter that I'm not able to solve,

I have a helper where it works as follows

function forms($a){
        for(i=0;i<=$a;i++){
             <input type='text' name='forms_$i'>
         }
 }

I previously used a code to generate the amount of inputs I wanted, but not very well how to get those values in my controller, because I need to get the values received in those forms and put them in the database.

If someone can help me in this part I would appreciate it a lot, either in a way to receive the values or a more practical way.

Thank you all.

Q: The other parts are correct in my code, I just do not know exactly how to get the values in my controllers to put them in the database.

    
asked by anonymous 28.08.2016 / 16:55

2 answers

2

To receive the post data in the controller use:

$valor = $this->input->post("input_name");

To save to the database use:

$this->db->insert("nome_tabela", $dados); //$dados deve ser um array

The question is how would your database structure be. But the model would be simple:

class FormularioModel extends CI_Model {

   public function inserir($dados) {
       $this->db->insert("nome_tabela", $dados); // lembrar de carregar biblioteca database
   }
}

Now if your table had two fields: field_name , field_value your method in the controller would be:

public function salvarDados() {
   $this->load->model("FormularioModel", "model");
   for($i = 0; $i < $a; $i++) {
      $dados = [
         "nome_campo" => "forms_$i",
         "valor_campo" => $this->input->post("forms_$i")
      ];
      $this->model->inserir($dados);
   }
}

Now a less viable alternative: if you have a multi-column table like: forms_1, forms_2, forms_3 ......

public function salvarDados() {
       $this->load->model("FormularioModel", "model");
       $dados = array();
       for($i = 0; $i < $a; $i++) {
          $dados["forms_$i"] = $this->input->post("forms_$i");
       }
       $this->model->inserir($dados);
   }
    
28.08.2016 / 20:38
2

Set the field names as an array

function forms($a){
    $r = '';
    for(i=0;i<=$a;i++){
        $r .= '<input type="text" name="nome_do_campo['.$i.']">';
    }
    return r;
}

echo forms(5);

To receive the data, just iterate through the array

if (is_array($this->input->post('nome_do_campo')) {
   foreach ($this->input->post('nome_do_campo') as $value) {
       echo $value.PHP_EOL.'<br>';
   };
};
    
28.08.2016 / 20:27