Use of loop in codeigniter

Asked

Viewed 124 times

0

Hello, all right with you?

I’m having a big problem in codeigniter that I’m not sure how to fix,

I have a helper where it works as follows

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

where I previously used a code to generate the amount of inputs I wanted, however not very well how to receive these values in my controller, because I need to take the values received in these forms and put them in the database.

If anyone can help me in this part I would greatly appreciate both in a way of receiving the values or a more practical way.

Thank you all.

P.S.: The other parts are correct in my code, I just don’t know exactly how to receive the values in my controllers to put them in the database.

2 answers

2

Set the name of fields 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 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>';
   };
};

2


To receive the post data in the controller use:

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

To save in the database use:

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

The question is what the structure of your database would look like. 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: fieldname, field your controller method 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 table with multiple columns 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);
   }
  • it worked at first, however when I increased the amount of data from [$data] it gave the following error 'Error Number: 1048 Column 'bin1' cannot be null INSERT INTO binaria (questao, bin1, bin2) VALUES ('2s121s12', NULL, NULL) Filename: C:/xampp/htdocs/SAO/system/database/Db_driver.php Line Number: 691'

  • I managed to resolve, thank you very much for your help

Browser other questions tagged

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