insert and update in the same table in codeigniter

0

I'm new to Codeigniter, I'm creating a Ws in php that inserts data in the database and then updates them depending on the user id and device and if not send me a message that corresponds to data inserted, data updated and if there is a repeated token that does not allow me to insert until a new token is entered.

this is the code in the controller:

 public function token(){
    $idToken = $this->input->post('id_token');
    $tokenDevice = $this->input->post('token');
    $device = $this->input->post('device');
    $Os = $this->input->post('so');
    $idUsuario = $this->input->post('id_usuario');
    $date = $this->input->post('date');

    $arrayToken = array('id_token' => $idToken,
                        'token' => $tokenDevice,
                        'device' => $device,
                        'so' => $Os,
                        'id_usuario' => $idUsuario,
                        'date' => $date);
    $data = $this->Api_model->token($arrayToken);
    $this->output->set_status_header(200);
    $apiResponse['message'] = $data['message'];
    $this->output->set_content_type('application/json');
    $this->output->set_output(json_encode( $apiResponse, JSON_PRETTY_PRINT));
}

and this is the code of the model:

public function token($data){
   $this->db->where('token', $data['token']);
   $this->db->where('id_usuario', $data['id_usuario']);
   $query= $this->db->get('tbtoken');
   if($query->num_rows() == 0) {
        if($query->num_rows() >= 0) {
            $object = array('token' => $data['token'],
                    'id_usuario' => $data['id_usuario'],
                    'device' => $data['device'],
                    'so' => $data['so']);
            $this->db->insert('tbtoken', $object);
            $data['message'] = "token guardado con exito";
            return $data;
        }else{
            $this->db->where('id_usuario', $data['id_usuario']);
            $object = array('token' => $data['token'],
                    'id_usuario' => $data['id_usuario'],
                    'device' => $data['device'],
                    'so' => $data['so']);
            $this->db->update('tbtoken', $object);
            $data['message'] = "token actualizado con exito";
            return $data;
        }
    }else{
        $data['message'] = "token repetido";
        return $data;
    }
}

I think the problem is in the model but I do not know how to solve it. Any help would be perfect.

    
asked by Rafael Rodriguez 03.08.2018 в 18:56
source

0 answers