Just need a hand understanding some simple database queries in ZF2. In ZF1 I have simple methods like this:
public function recordset()
{
// listing of all records
$db = Zend_Registry::get('db');
$sql = "SELECT " . $this->_selectlist() .
" from customer c";
$r = $db->fetchAll($sql);
return $r;
}
In ZF2, how would I do the same? I have tried the following, but this just returns what looks like a "Result" object, but all I want is an array like ZF1 did with fetchAll. If I have to iterate the result object only to provide the array later, which then must be iterated over again, it just seems like some duplication of effort.
Anyway, here's what I have in ZF2 so far:
//above the controller start I have: use Zend\Db\Adapter\Adapter as DbAdapter;
public function blaAction()
{
$db = new DbAdapter(
array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=mydb;host=localhost',
'username' => 'root',
'password' => '',
)
);
$sql = 'select * from customer';
$stmt = $db->query($sql);
$results = $stmt->execute();
$this->view->data = $results;
return $this->view;
}
In the output, I get this:
object(Zend\Db\Adapter\Driver\Pdo\Result)#197 (8) {
["statementMode":protected]=> string(7) "forward" ["resource":protected]=> object(PDOStatement)#195 (1) {
["queryString"]=> string(22) "select * from customer"
} ["options":protected]=> NULL ["currentComplete":protected]=> bool(false) ["currentData":protected]=> NULL ["position":protected]=> int(-1) ["generatedValue":protected]=> string(1) "0" ["rowCount":protected]=> NULL
}
However, if I change $results to $results->count();
I do indeed see a record count. How do I get to the data though as an array? (a full recordset)
At one point I did see something like: $results->current()
But that only returned a single record.
Just a side note. I do see all the table abstract classes I could use, but at this point in my learning, I don't want to do that. I just want some simple on-demand queries that return arrays like they did in ZF1. In ZF2, there's seems to be way too much "wiring up" of things in configs and stuff that just seem like overkill. But, as a framework, I like the flexibility and the main app I am working on in ZF1 could really benefit from the modularity of ZF2. (otherwise I'd probably go with other framework)
Please forgive my ignorance, and thanks very much for any help!
PDO
did you look for a method likefetchAll
onZend\Db\Adapter\Driver\Pdo\Result
? Otherwise you need to loop over the$result
like you would with an executed PDOStatement i believe.$result->getResource()->fetchAll(PDO::FETCH_ASSOC)
to get around it. Though overall id never recommend Zend_Db either in 2.x or 1.x... Instead id go with Doctrine - DBAL if you just want abstraction or the full ORM if you want that.