How to get num rows in Codeigniter?

by haylee.mertz , in category: PHP Frameworks , 2 years ago

How to get num rows in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by jerad , 2 years 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.

Member

by jasen , a year ago

@haylee.mertz 

To get the number of rows returned by a query in CodeIgniter, you can use the num_rows() method of the Query Builder or Database Library.


Here is an example of how to do it:

  1. Using the Query Builder:
1
2
3
$query = $this->db->get('your_table_name');
$row_count = $query->num_rows();
echo $row_count;  // number of rows


  1. Using the Database Library:
1
2
3
4
$sql = "SELECT * FROM your_table_name";
$query = $this->db->query($sql);
$row_count = $query->num_rows();
echo $row_count;  // number of rows


Make sure to replace 'your_table_name' with the actual name of your table in the above examples.


Note: The num_rows() method should always be called after executing the query and fetching the result.