Correct way to return the number of results using CodeIgniter

0

I wrote 2 possibilities to return the number of results using CodeIgniter, as 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: What is the correct way and why? Is it indifferent? What about performance for MySQL?

    
asked by anonymous 04.11.2015 / 23:17

1 answer

1

The two ways of getting the total number of results from the database table are then correct, for however much they are written in different ways they then arrive at the same end to which they were created.

But in terms of performance, the first one is faster because the query in the database only returns the total amount of records in the users table with the count while the second method returns the records of the bank that will not be used and then the count is done with the num_rows method of the CI.

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

05.11.2015 / 12:59