Condition IF codeigniter - Check if data exists in the database (model)

0

I have the following method to get data in codeigniter.

// Obter Fase
public function obter_fase($id)
{
    $this->db->from($this->tbl_empresa_fase);
    $this->db->select("tbl_empresa_fase.*, IF(tbl_empresa_fase.crud = 'C', 'R', 'C') as crud", FALSE);
    if (is_array($id))
    {
        $this->db->where_in('campanha_id',$id);
    }
    else
    {
        $this->db->where('campanha_id',$id);
    }
    $this->db->order_by('campanha_id');
    $query = $this->db->get();
    $item = $query->result_array();
    return $item;
}

It works, but if the ID being searched does not exist in the database, an error is returned and with the above method, this is already expected.

For this reason, I want to know if there is a possibility of creating a condition that checks whether the searched ID exists in the database.

If yes, return result_array , otherwise, return return [] .

    
asked by anonymous 14.12.2017 / 19:56

1 answer

1

You can simply check the variable $item before the time to return the function value

//retornando com um if
if ($item) {
     return $item;
} else {
     return [];
}

//retornando com um ternário
return empty($item) ? [] : $item;

So I saw the empty select in the IN() error message, so this same check can be performed before the query

// Obter Fase
public function obter_fase($id)
{
    if(empty($id) && is_numeric($id)) return []; // aqui verifica se o id passado é um número e se há valor
    $this->db->from($this->tbl_empresa_fase);
    $this->db->select("tbl_empresa_fase.*, IF(tbl_empresa_fase.crud = 'C', 'R', 'C') as crud", FALSE);
    if (is_array($id)) {
        $this->db->where_in('campanha_id',$id);
    } else {
        $this->db->where('campanha_id',$id);
    }
    $this->db->order_by('campanha_id');
    $query = $this->db->get();
    $item = $query->result_array();
    return empty($item) ? [] : $item;
}
    
14.12.2017 / 20:05