zend-framework2

How do i execute queries and fetch data from the result in ZEND 2?


I want to execute queries in zend2 in a old fashion way. I want to write queries and execute it. I do not want to use the function save(), update(), delete(). This is my model:

namespace Application\Model;
    
use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\ResultSet;
    
class UsersTable extends AbstractTableGateway {
    
    public function __construct(Adapter $adapter) {
        $this->adapter = $adapter;
    }
    
    public function fetchAll() {    
        $results  = $this->adapter->query("SELECT * FROM users");
        return $results->execute();
    }
}

In the function fetchAll I want to execute the query "select * from users". How can i do that ? The result of this is :

object(Zend\Db\Adapter\Driver\Pdo\Result)#243 (8) {
  ["statementMode":protected]=>
  string(7) "forward"
  ["resource":protected]=>
  object(PDOStatement)#241 (1) {
    ["queryString"]=>
    string(19) "SELECT * FROM users"
  }
  ["options":protected]=>
  NULL
  ["currentComplete":protected]=>
  bool(false)
  ["currentData":protected]=>
  NULL
  ["position":protected]=>
  int(-1)
  ["generatedValue":protected]=>
  string(1) "0"
  ["rowCount":protected]=>
  NULL
}

Solution

  • you will make an Array

    public function fetchAll() {
        $stmt = $this->adapter->query('SELECT * FROM user');
        $result = $stmt->execute();
        if($result->count() > 0) {
            $returnArr = array();
            while ($result->valid()) {
                $returnArr[] = $result->current();
                $result->next();
            }
            if(count($returnArr) > 0) {
                return $returnArr;
            }
        }
        return FALSE;
    }