IF condition codeigniter - Check whether data exists in the database(model)

Asked

Viewed 642 times

0

I have the following method to obtain 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 expected.

For this reason, I want to know if there is possibility to create a condition that checks if the ID sought exists in the database.

If yes, returns the result_array, if not, returns return [].

  • Before the return what I have in $item when the $id there is no?

  • If there is no error..

  • What mistake, what line?

  • I will try your answer, but check the error:: Error Number: 1064 You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near ') ORDER BY campanha_id' at line 3 SELECT tbl_empresa_fase. *, IF(tbl_empresa_fase.crud = 'C', 'R', 'C') as crud FROM tbl_empresa_fase WHERE campanha_id IN() ORDER BY campanha_id

1 answer

1


You can simply check the variable $item before returning the function value

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

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

From what I saw in the error message select is empty inside the IN(), then 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;
}
  • With this I still have this error: SELECT tbl_empresa_fase. *, IF(tbl_empresa_fase.crud = 'C', 'R', 'C') as crud FROM tbl_empresa_fase WHERE campanha_id IN() ORDER BY campanha_id

  • Message: Call to Undefined Function is_number()

  • I took the is_number and it worked...

  • I misnamed the function, it’s id_numeric(), hehe

Browser other questions tagged

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