Select max ID in PHP

0

I am doing a simulation of a codeigniter system which works with MVC. I'm trying to pass the last ID of my "users" table to a field called "user_id " from my table "clients" (Since they are related to an FK) and everything so that from a form to register a Client that will be assigned the last Registered User . For this I have tried to do the following:

On my controller:

public function registro_cliente(){
        $id_usuario = $this->Clientes_model->lastID(); //llamada a mi modelo
        $nombre = $this->input->post("nombre"); //es el que paso en el formulario
    }

$data = array('usuario_id' => $id_usuario,
              'nombre' => $nombre );
}

And in the model I have the following:

public function lastID(){
    $this->db->select_max("id_usuarios");
    $this->db->where("borrado", "1");
    $this->db->from("usuarios");
    $resultados = $this->db->get();
    return $resultados->result(); }

But the result of that throws me an ARRAY and the following comes out:

  

Message: Array to string conversion || I only notice that in the insertion it says ARRAY (But obviously I would not insert that, that's why the error message)

I've also tried this with the following:

public function lastID(){
    $this->db->select_max('id_usuarios');
    $this->db->from('usuarios');
    $query=$this->db->get()->row(); }

and throws the following:

  

Column 'user_id' can not be null || Again (below the error) throws the NULL as what was trying to insert.

And I've been trying many other ways but without a concrete result, I looked for and nothing. I need help, please ...

    
asked by González 06.12.2017 в 00:43
source

1 answer

1

Try printing the variable $ userid in the controller with print_r so that you can see its structure. The return of the model is not a string, but an array with an object inside and the problem is generated in this part of the code:

 $data = array('usuario_id' => $id_usuario, 'nombre' => $nombre );

You can access the value of the userid column in the following way in the controller

 $id_usuario = $this->Clientes_model->lastID(); //llamada a tu modelo
 echo ($id_usuario[0]->id_usuarios); // este si deberia ser un string

I recommend you try printing with print_r the variable $ userid so you understand better.

I hope my answer is helpful:)

    
answered by 06.12.2017 / 14:34
source