Duplicate records in the database table

Asked

Viewed 48 times

0

I have the following model:

function validarQuestionario()
{

    if(is_array($this->input->post('resposta[]')) || is_object($this->input->post('resposta[]')))
    {
        foreach ($this->input->post('resposta[]') as $single_resp) 
        {

            foreach ($this->input->post('idMarcacao[]') as $single_id)
            {
                $data['respostaAluno'] = $single_resp;
                $data['idMarcacao'] = $single_id;
                $this->db->insert('tbdquestionario', $data);
            }

        }
    }


}

Instead of being recorded 10 lines that would be the correct value, is being logged 100 lines in the bank.

  • if the answer[] is the event[] is 10 each 10 x 10 = 100 correct?

  • Exact, but how could I recover the data to do Insert without the foreach?

  • Just to confirm, are you using Codeigniter? By the syntax it seems to be it, so I entered the tag, but if it is not I can remove it.

  • Will you do the for normal for($i = 0; $i < count(resposta[]);$i++) { resposta[$i] ... // assim por diante }

  • @Woss, it’s Codeigniter yes!!

1 answer

1


I don’t use Codeigniter to have full authority over what I will talk about, but I will start from basic PHP analysis:

whereas $this->input->post('resposta[]') return a array with the values in the field resposta[], that $this->input->post('idMarcacao[]') also return a array with the values in the field idMarcacao[] and that both arrays are the same size (I won’t worry about validating this), you can do:

$respostas = $this->input->post('resposta[]');
$ids = $this->input->post('idMarcacao[]');

$data = array_map(function ($resposta, $id) {
  return compact('resposta', 'id');
}, $respostas, $ids);

$this->db->insert_batch('tbdquestionario', $data);

And only. Supposing that the array of answers be something like ['a', 'c'] and the array of ids [1, 2], the function array_map will generate a array in format:

$data = array (
  0 =>
  array (
    'resposta' => 'a',
    'id' => 1,
  ),
  1 =>
  array (
    'resposta' => 'c',
    'id' => 2,
  ),
);

And, as the documentation, the method insert_batch may receive a array of arrays to insert them at once (it is not feasible to do one by one), unless you want to manage the transactions independently.

Homework: why a function that inserts into the database is called validarQuestionario?

  • Opa, the name of this function really shouldn’t be this, I changed. Thanks for warning.

  • I changed the code to what you suggested, but returned this error (edited by placing the error photo).

  • @Ckpy Because it needs to be associative array indicating the column name of each value... I think you can solve this from what I passed

  • It worked, buddy. Thank you very much, really

Browser other questions tagged

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