user911952 user911952 - 2 months ago 21
PHP Question

Zend Framework 2 - Database connection

Trying to wrap my head around the new concepts of Zend Framework 2.0.

I'm trying to connect to a database, and to get that connection in a controller or model.
Nothing fancy, just the pure connection to run queries against.

So this is my current code:

//module.config.php
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=DBNAME;host=HOSTNAME,
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
'username' => 'USERNAME',
'password' => 'PASSWORD',
),
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);


What am I doing wrong?

Answer

Create db.local.php in your ./config/autoload folder and add the following content

return array(
'db' => array(
    'driver'         => 'Pdo',
    'dsn'            => 'mysql:dbname=zenBlog;host=localhost',
    'username'       =>'root',
    'password'      =>'',
    'driver_options' => array(
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
    ),
),
'service_manager' => array(
    'aliases' => array(
'db' => 'Zend\Db\Adapter\Adapter',
),
),);

in your controller $this->getServiceLocator()->get('db'); to access to database.