difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

后端 未结 8 1670
南方客
南方客 2020-12-13 17:50

In a scenario I need to know the count of recordset a query will return, which in codeigniter can be done by $query->num_rows() or $this->db->cou

相关标签:
8条回答
  • 2020-12-13 18:25

    There are two ways to count total number of records that the query will return. First this

    $query = $this->db->query('select blah blah');  
    return $query->num_rows();
    

    This will return number of rows the query brought.

    Second

    return $this->db->count_all_results('select blah blah');
    

    Simply count_all_results will require to run the query again.

    0 讨论(0)
  • 2020-12-13 18:25

    Simply as bellow;

    $this->db->get('table_name')->num_rows();
    

    This will get number of rows/records. however you can use search parameters as well;

    $this->db->select('col1','col2')->where('col'=>'crieterion')->get('table_name')->num_rows();
    

    However, it should be noted that you will see bad bad errors if applying as below;

    $this->db->get('table_name')->result()->num_rows();
    
    0 讨论(0)
  • 2020-12-13 18:28

    With num_rows() you first perform the query, and then you can check how many rows you got. count_all_results() on the other hand only gives you the number of rows your query would produce, but doesn't give you the actual resultset.

    // num rows example
    $this->db->select('*');
    $this->db->where('whatever');
    $query = $this->db->get('table');
    $num = $query->num_rows();
    // here you can do something with $query
    
    // count all example
    $this->db->where('whatever');
    $num = $this->db->count_all_results('table');
    // here you only have $num, no $query
    
    0 讨论(0)
  • 2020-12-13 18:29

    Total number of results

    $this->db->count_all_results('table name');
    
    0 讨论(0)
  • 2020-12-13 18:32

    Which one is better and what is the difference between these two Its almost imposibble to me, someone just want to get the number of records without re-touching or perform another query which involved same resource. Furthermore, the memory used by these two function is in same way after all, since with count_all_result you still performing get (in CI AR terms), so i recomend you using the other one (or use count() instead) which gave you reusability benefits.

    0 讨论(0)
  • 2020-12-13 18:37

    $this->db->count_all_results is part of an Active Record query (preparing the query, to only return the number, not the actual results).

    $query->num_rows() is performed on a resultset object (after returning results from the DB).

    0 讨论(0)
提交回复
热议问题