Codeigniter - Recover ID

Asked

Viewed 921 times

2

I need to retrieve the last ID inserted in a table and pass this ID to the field of another function.

It is possible to recover in this way ?

$negociacao = array(
        'id'             => $neg->id,
        'dt_negociacao'  => $neg->dt_negociacao,
        'atualizar'      => $neg->atualizar,
        'contrato_id'    => $neg->contrato_id,
        'id_finalizacao' => $neg->id_finalizacao,
        'crud'           => "C",
    );
$this->db->insert('tbl_devedor_negociacao', $negociacao);
$negociacao_id = $this->db->insert_id(); //Armazenar ID recuperado
$this->set_negociacao_id($negociacao_id); // Setter váriável ID armazenado

// setter ID
private function set_negociacao_id($negociacao_id = null)
{       
    return $negociacao_id;
}

// getter ID
private function get_negociacao_id()
{
    $this->set_negociacao_id();
}

// Atribuir ID recuperado Aqui
'negociacao_id'  => $this->set_negociacao_id(),
  • Your get/set looks inverted and a little weird. This code gives some error?

  • No error. In function set_negociacao_id, if I place echo or print_r, it displays the last inserted ID, but when Return, it displays null.

  • set is to save/assign and get to return. The set has a return and the get does nothing...

  • My intention is to retrieve this ID from an insert and assign this ID in a field from another function

1 answer

1


Get methods must return the value of something and set save or assign a value to a class property.

// setter ID
private function set_negociacao_id($negociacao_id = null)
{       
    return $negociacao_id;
}


private function get_negociacao_id()
{
    $this->set_negociacao_id();
}

The line below returns the value that was passed as argument which does not make much sense since it is not assigned anywhere or worse because it creates a method that returns its own input?

$this->set_negociacao_id($negociacao_id); // Setter váriável ID armazenado

If I understand correctly, to solve the problem first the set must save the value passed in a class property the corresponding code is :

private $negociacao_id;
//código omitido...

public function set_negociacao_id($negociacao_id)
{       
   $this->negociacao_id = $negociacao_id;
}

The get must return the property value only:

public function get_negociacao_id()
{
    return $this->negociacao_id;
}
  • but there I have it Missing argument 1 for Devedor_model::set_negociacao_id(), called in in function private function set_negociacao_id($negociacao_id)

  • @Wagnerson you can’t call the set without passing a value because it is for writing. If you only need to read the value use the get

  • Oops! I was doing something wrong.

  • It worked! Thank you very much..

Browser other questions tagged

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