How to get num rows in Codeigniter?

by haylee.mertz , in category: PHP Frameworks , a year ago

How to get num rows in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 5 months ago

@haylee.mertz 

In Codeigniter, you can use the num_rows() method of the database class to get the number of rows returned by a SELECT statement. Here's an example:

1
2
3
4
5
$this->db->select('*');
$this->db->from('mytable');
$query = $this->db->get();

$num_rows = $query->num_rows();


This will execute a SELECT statement that retrieves all rows from the mytable table, and then it will store the number of rows returned in the $num_rows variable.


Alternatively, you can use the count_all_results() method to get the number of rows that would be returned by a SELECT statement without actually executing the query:

1
$num_rows = $this->db->count_all_results('mytable');


This can be more efficient than executing the query and then calling num_rows(), because it avoids the overhead of returning and processing the result set. However, it only works for SELECT statements that do not have a WHERE clause, GROUP BY clause, or HAVING clause.