3

I have this function in my Carros_model.php that is used to bring the last insertions and display them in the dashboard:

public function select_all($limit = 3)
{
    $this->db
        ->select('marca.nome_marca,'
               . 'combustivel.nome_combustivel,'
               . 'cambio.descricao_cambio,'
               . 'DATE_FORMAT(carro.data_criacao, "%d/%m/%Y") as criacao,'
               . 'DATE_FORMAT(carro.data_modificacao, "%d/%m/%Y") as modificacao,'
               . 'carro.*')
        ->from('carro')
        ->join('marca', 'marca.id = carro.id_marca')
        ->join('combustivel', 'combustivel.id = carro.id_combustivel')
        ->join('cambio', 'cambio.id = carro.id_cambio')
        ->order_by('carro.id', 'DESC')
        ->limit($limit, 0);

    $query = $this->db->get();

    foreach ($query->result_array() as $row) {
        $data[] = $row;
    }

    $query->free_result();

    return $data;
}

It works fine, but I discovered that if the table is empty, the error

Fatal error: Call to a member function result_array() on boolean

is thrown. How do I solve this?

1
  • just check the content of the variable $query before the loop, if it's an empty array then you can't call result_array on it Commented Dec 1, 2015 at 19:31

2 Answers 2

11

You should be checking to see if the query worked/has any rows before trying to get its results. If the table is empty, then the query won't do anything.

$query = $this->db->get();

$data = array();
if($query !== FALSE && $query->num_rows() > 0){
    foreach ($query->result_array() as $row) {
        $data[] = $row;
    }
}

return $data;

P.S. There's no reason to use a loop over $query->result_array(), you can just return that. It's already an array of rows.

$query = $this->db->get();

$data = array();
if($query !== FALSE && $query->num_rows() > 0){
    $data = $query->result_array();
}

return $data;
Sign up to request clarification or add additional context in comments.

2 Comments

Nice. Now I must find a way to check in my view to see if there is any data, because it is accusing Invalid argument supplied for foreach().
@mfgabriel92: Try is_array().
0

Make this change in your code (Add $data array after the $query):

$query = $this->db->get();
$data = Array();
foreach ($query->result_array() as $row) {
    $data[] = $row;
}

This happens because $data variable doesn't exist unless you create an empty variable before the loop in case there are no results.

1 Comment

While a good idea, this isn't the source of the issue. You can do $data[] = ...; without declaring $data, you shouldn't but you can. See: php.net/manual/en/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.