Home » Php » php – Zend: Select object: How do I replace the selected columns set by from()?

php – Zend: Select object: How do I replace the selected columns set by from()?

Posted by: admin July 12, 2020 Leave a comment


first of all, that’s what I’m trying to do:

In one of my classes in the library I want to count the total amount of rows of a search result. The class uses a select object set by the appendant model of the search result. My problem is now, this select() has already set the requested columns by from(), but to simply count the rows I just want to select the id, because the website has to to be performant. I can’t simply change the values of the object, because I’m using it in the library and the variables are protected. Unfortunately, Zend has no function for the mySql count command and I don’t want to use static mySql code, because it could be, that we switch our database system in the future.

Now here’s my question:

Is there any possibility by Zend_Select how I could change the selected columns?

How to&Answers:

Try this:

       ->from('thetable', 'COUNT(*)');

replacing the ‘thetable’ with the correct table name.


This is from a project and isn’t tested, but one of these should work.

$select->from(array("table_name" => "table_name"), array("my_col" => "COUNT(id)"));


$select->from(array("table_name"), array("my_col" => "COUNT(id)"));

This is the same as

SELECT COUNT(id) as my_col FROM table_name 

Hope that helps



This one didn’t work for me (I needed to select only from one joined table):

       ->from('thetable', 'COUNT(*)');

Maybe because I had some joins. But nevertheless, here’s the solution: to use reset() and then columns():

        ->from(['t1' => 'table1'])
        ->join(['t2' => 't2'], 't1.id = t2.t1_id')

Just FYI, the version of Zend Framework is 1.12


To use a mysql command in a select, you need to use Zend_Db_Expr:

$select = $this->select()
            ->from('myTable', new Zend_Db_Expr('COUNT(id) as count'));
echo $select; //SELECT COUNT(id) as count FROM myTable;