Last active
February 24, 2017 09:37
-
-
Save bitkorn/fb09469949d2a750f4df670dc87e885d to your computer and use it in GitHub Desktop.
Short way to fetch all from SQL database with ZF2 \Zend\Db\Adapter\Adapter (no ZF2 \Zend\Db\TableGateway\AbstractTableGateway).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Foo; | |
use Zend\Db\Adapter\Adapter; | |
use Zend\Db\Adapter\ParameterContainer; | |
class A | |
{ | |
/** | |
* | |
* @var \Zend\Db\Adapter\Adapter | |
*/ | |
protected $adapter; | |
/** | |
* | |
* @param Adapter $adapter | |
*/ | |
public function setDbAdapter(Adapter $adapter) | |
{ | |
$this->adapter = $adapter; | |
} | |
/** | |
* In my case fetchAll() is a PDO function. So i can use the parameter \PDO::FETCH_ASSOC. | |
* In another case, it may not exist. | |
* @return array | |
*/ | |
public function getAs() | |
{ | |
$parameter = new ParameterContainer(['c']); | |
$stmt = $this->adapter->createStatement('SELECT * FROM a WHERE a_column = ?', $parameter); | |
/* | |
* or with query() | |
*/ | |
// $stmt = $this->adapter->query('SELECT * FROM a'); | |
$result = $stmt->execute(); | |
if ($result->valid() && $result->count() > 0) { | |
return $result->getResource()->fetchAll(\PDO::FETCH_ASSOC); | |
} | |
return []; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment