count()
public function count(string $table): int
Description
Counts the total number of records in a specified database table. This method validates table existence, executes a COUNT(*) query, and returns the result as an integer. It provides a simple way to get the total record count from any table.
Parameters
| Parameter | Type | Description | Default | Required |
|---|---|---|---|---|
| table | string | The name of the database table to count records from. | - | Yes |
Return Value
| Type | Description |
|---|---|
| int | The total number of records in the specified table, cast to integer. |
Exceptions
- RuntimeException - If the specified table does not exist in the database.
- PDOException - If there's a database error during query execution.
Example #1: Counting Users
The code sample below demonstrates how to count the total number of users in the 'users' table.
PHP
$total_users = $this->db->count('users');
echo "Total users in the system: " . $total_users;Example #2: Counting Products with Conditional Logic
The code sample below demonstrates how to use the count result in conditional logic.
PHP
$product_count = $this->db->count('products');
if ($product_count > 0) {
echo "There are " . $product_count . " products available.";
} else {
echo "No products found in the catalog.";
}Example #3: Comparing Counts Across Multiple Tables
The code sample below demonstrates how to count records from different tables for comparison.
PHP
$active_users = $this->db->count('users');
$pending_orders = $this->db->count('orders');
$total_products = $this->db->count('products');
echo "System Statistics:";
echo "- Active Users: " . $active_users . "";
echo "- Pending Orders: " . $pending_orders . "";
echo "- Available Products: " . $total_products;Important Notes
- The
$tableparameter is required. - The method validates that the table exists before executing the COUNT query.
- Returns the count of ALL records in the table (no WHERE clause is applied).
- The result is cast to integer using
(int)type casting. - Uses
COUNT(*)which counts all rows including those with NULL values. - The SQL query uses
AS totalalias for the count result. - If debug mode is enabled, the generated SQL query will be displayed before execution.
- For large tables, this operation can be resource-intensive; consider caching the result if counting frequently.
- To count with conditions, use
query_bind()with a custom COUNT query containing WHERE clauses.