How to use mysql queries in Zend Framework 2

In this tutorial I will explain how to use mysql in Zend Framework 2.

First, I will create a new model called categories, and in my module.php file I will add:

public function getServiceConfig()
return array(
'factories' => array(
'Mashog\Model\Categories' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new \Mashog\Model\Categories('categories', $dbAdapter);
return $table;

In my Controller, I will connect the created model:

$select = $this->getCategoriesTable()->fetchAll();

Now, I will write a sql query in my model:

public function fetchAll()
$statement = $this->adapter->query('SELECT * FROM categories');
$results = $statement->execute();
return iterator_to_array($results); // will return an array

Video tutorial:

Leave a Comment