Oleg Bronzov Tue Nov 30 06:35:19 -0500 2010

Subject: mysql_num_rows

How can i get number of rows in the table?

For example i whant to organize paging, i need to now number of rows in the table but i dont whant to select all entries becouse it can be 1000000.


Srdjan Lisica Tue Nov 30 06:50:57 -0500 2010

I have the same question.

Srdjan Lisica Tue Nov 30 07:06:48 -0500 2010

Oleg:
I found a provisory solution, it's not totally efficent but it does work :-P:
http://pastebin.com/L9x96ZZs
Cheers.

Oleg Bronzov Tue Nov 30 07:40:40 -0500 2010

I understand that it will be work, it feth all entries from table and its ok if you have not many rows in the table.
But if you have many rows in the table (for example million or more) its not good think to fetch all entries becouse it will be very big dump that will send from database server to php.

Oleg Bronzov Tue Nov 30 07:44:36 -0500 2010

I think this solution is more correct

User::find_by_sql('SELECT count(ID) FROM users')

Oleg Bronzov Tue Nov 30 07:59:13 -0500 2010

you can write class that extends from ActiveRecord\Model and use it for base model class

class Model extends ActiveRecord\Model
{
    public static function find_num_rows()
    {
        return self::find('all', array('select' => 'count(*) AS num_rows'));
    }
}
Oleg Bronzov Tue Nov 30 08:07:49 -0500 2010

or this

class Model extends ActiveRecord\Model
{
    public static function find_num_rows()
    {
        $array = self::first(array('select' => 'count(*) AS num_rows'))->attributes();

        return $array['num_rows'];
    }
}
Srdjan Lisica Tue Nov 30 10:17:48 -0500 2010

That's clearly much better ;-)

Oleg Bronzov Tue Nov 30 10:55:51 -0500 2010

)) but my think is it must be in core of the ORM

Jacques Fuentes Tue Nov 30 21:09:58 -0500 2010

Please refer to the docs

The code would be

$num = SomeModel::count();
echo $num; # 4

Raja Amer Khan Wed May 01 05:43:22 -0400 2013

Use PHP array count on the resulted object.

Example:

$userObj = User::find('all', array('conditions' => array('user_type' => 'admin')));

count($userObj);

This would act as mysql_num_rows()

(1-10/10)