CodeIgniter框架对数据库查询结果进行统计

时间:2022-07-04 07:57:14

假设有一个user表,如果要查询符合条件sex=male的记录数量,有下面几种方法:

方法一:先取回所有符合条件的记录,再count

$res = $this->db->query("select * from user where sex='male'")->result_array();
$num = count( $res );

  不推荐上面的做法,因为我们的目的不是取回表中的数据,只需要具体的行数。取回数据的过程就是一个多余的操作,会浪费很多资源!

 

方法二:在SQL语句中使用count(*)

$sql = "select count(*) num from user where sex='male'";
$res = $this->db->query($sql)->row_array();
$num = $res['num'];

  

方法三:在取结果之前打印query返回值,通过获取query内部的属性名来获取num_rows,注意全是属性,不能使用数组格式访问:

$sql = "select *  from user where sex='male'";
$res = $this->db->query($sql);
print_r($res);

  访问程序,打印结果如下:

CI_DB_mysqli_result Object
(
    [conn_id] => mysqli Object
        (
            [affected_rows] => 130
            [client_info] => mysqlnd 5.0.11-dev - 20120503 - $Id: ....... $
            [client_version] => 50011
            [connect_errno] => 0
            [connect_error] => 
            [errno] => 0
            [error] => 
            [error_list] => Array()
            [field_count] => 25
            [host_info] => Localhost via UNIX socket
            [info] => 
            [insert_id] => 0
            [server_info] => 5.1.73-log
            [server_version] => 50173
            [stat] => ........
            [sqlstate] => 00000
            [protocol_version] => 10
            [thread_id] => 28698933
            [warning_count] => 0
        )
    [result_id] => mysqli_result Object
        (
            [current_field] => 0
            [field_count] => 25
            [lengths] => 
            [num_rows] => 130
            [type] => 0
        )
    [result_array] => Array()
    [result_object] => Array()
    [custom_result_object] => Array()
    [current_row] => 0
    [num_rows] => 
    [row_data] => 
)

  可以注意到这里面有一个conn_id->affected_rows和 result_id->num_rows,所以可以通过这两个值获得结果集的记录数量:

echo $res->conn_id->affected_rows;
echo $res->result_id->num_rows;

  

  第三种方法并不是很好的选择,推荐第二种,提到第三种方法的目的在于了解query的返回值,然后可以自己根据结果写一些helper来处理一些事情