Correct way to return the number of results using Codeigniter

Asked

Viewed 1,811 times

0

I wrote 2 possibilities to return the number of results using Codeigniter, follows:

public function get_num_indicados($id_usuario)
{
    $query = $this->db->query("SELECT count(id_patrocinador) as num FROM usuarios WHERE id_patrocinador = ?", array($id_usuario));

    $row = $query->row();

    return $row->num;
}

public function get_num_indicados($id_usuario)
{
    $query = $this->db->query("SELECT * FROM usuarios WHERE id_patrocinador = ?", array($id_usuario));

    return $query->num_rows();
}

Doubt: Which is the right way and why? Indifferent? And how about performance for Mysql?

  • Buddy, I usually use either one, but I also use Count($this->model->Function()); which also solves...

1 answer

1


The two ways to get the total number of results from the database table then correct, because as much as they are written in different ways they then come to the same end that they were created.

But in terms of performance, the first is faster, because the query in the database only returns the total amount of records in the table users with the function Count Mysql, while the second method returns the database records that will not be used and then the records are counted with the method num_rows of the IC.

If the number of records in the table users be little the difference in performance may be indifferent, but if the table has many records the difference may be noticeable in performance.

Browser other questions tagged

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