Search code examples
phpmysqlzend-frameworkzend-dbzend-db-table

Getting table object(App_Model_TableName) as fetch result (Zend Framework)


Right now, I'd wrote a function in my model as:

public function getRowsByZipCode($zip)
{
    // SQL to get all the rows with the given zip code
    $stmt = $this   -> getAdapter()
                    -> query(  "SELECT *
                                FROM 
                                    table_name
                                WHERE
                                    table_name.status = 1 AND 
                                    table_name.zip={$zip}");     
    $resultRows = $stmt->fetchAll(); 

    // -------------------------------------------------------- //        
    // Convert result set to an array of objects
    $resultObjects = array();
    // If there is atleast one row found in DB
    if(count($resultRows) > 0) 
    {
        // Loop throguh all the rows in the resultset
        foreach($resultRows as $resultRow) {
            // Create table row and fill it with the details got from DB
            $h = $this->createRow();
            $h->setFromArray($resultRow);

            // Add to the array
            $resultObjects[] = $h;
        }
    }
    return $resultObjects;
    // -------------------------------------------------------- //
}

Which is working perfectly as I needed. And it is returning me an array that contains the tables row objects(App_Model_TableName Objects), which will be used later for further operations like save and delete etc.

What I really want is to remove the code that loop through the rows I got from the result set and converting each row to an object of App_Model_TableName that I'd wrote inside the comments // --- //.

Thanks in advance.


Solution

  • Finally, I had found the solution:

    public function getRowsByZipCode($zip)
    {
        // SQL to get all the rows with the given zip code
        $stmt = $this   -> getAdapter()
                        -> query(  "SELECT *
                                    FROM 
                                        table_name
                                    WHERE
                                        table_name.status = 1 AND 
                                        table_name.zip={$zip}");     
        $resultObjects= array();
        while($data = $stmt->fetch())
        {
            $h = $this->createRow();
            $h->setFromArray($data);
    
            // Add to array
            $resultObjects[] = $h;;
        }
        return $resultObjects;
    }
    

    I had removed the code that do the fetchAll() and loop through each row in the resultset. Now, I am taking each row from the resultset and creating an row of App_Model_TableName object using the data we got from the resultset.

    Working perfectly for me.