Search code examples
phpzend-framework2

How to count number of rows within Zend Framework 2


I need to count result rows of MySql query. here I extended TableGateway class to my class this is my code.

public function get_num_of_rows(){
    $sql = 'SELECT count(q_no) FROM questions';

    //code ????????????????
    $result = $this->select();

    return $result;
}

So how I execute SELECT count(q_no) FROM questions ?


Solution

  • There is no need to write own sql query. When you do $this->select(), you get an instance of Zend\Db\ResultSet\ResultSet. ResultSet has method count.

    $result = $this->select();
    return $result->count(); 
    

    But do not forget to add 'options' => array('buffer_results' => true) to your DB adapter.

    UPDATE:

    It is the stupidest thing I've ever written somewhere. Always return from resource required only data. Here you need 1 scalar only. So https://stackoverflow.com/a/13810175/1353837 is correct.