objSQL Helper Method: Row Count
The obj_row_count() helper method returns the number of rows from a select count() query and is called from the objSQL class. This helper method is dependant only on the connection instance and can be called anywhere within a query block.
The SQLite3 and Firebird drivers do not have a native PHP num rows method and use a simulated num rows query, but it is very inefficient and can time out on smaller recordsets. The SQLite3 PDO driver returns 0 and the SQLSRV PDO driver returns -1 from the PHP rowCount() method. The obj_row_count() helper method is recommended for all situations requiring an accurate and efficient num rows count.
- The $table name argument is required.
- The optional $cols argument specifies which column(s) to count and is entered as a comma delimited string. Entering an empty value is equivilent to an asterisk (*).
- The optional $where argument allows you to limit which rows are selected and only requires the column and its value. You can use any of the normal operators used in SQL statements:
- "color IN ('blue','red')"
- "color='red' AND material='leather'"
- "brand LIKE 's%'"
- "price BETWEEN 200 AND 400"
Returns: Unsigned integer or -1 if undetermined or failure
<?php
//usage: $num_rows = $dbh->obj_row_count( $table, $cols, $where )
try
{
$num_rows = $dbh->obj_row_count( "mytable", "id", "l_name='Jones'" );
if ( $dbh->obj_error() )
throw new Exception( $dbh->obj_error_message() );
echo "<p>Your query returned $num_rows results</p>";
}
catch ( Exception $e )
{
//log error and/or redirect user to error page
}
?>