Zend Framework 2 - Database Connection

Trying to wrap yourself around new Zend Framework 2.0 concepts.

I am trying to connect to a database and get this connection in the controller or model. Nothing out of the ordinary, just a clean connection to execute requests 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?

+5
source share
2 answers

Create db.local.php in the folder. / config / autoload 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 the database.

+9
source

This is what my local.php file looks like in config \ autoload \ local.php.

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

Now use this to create the database adapter:

$adapter = $this->getServiceLocator()->get('adapter');

Create sql status and set $ sql variable. Now do the following:

$statement = $adapter->createStatement($sql);
$result = $statement->execute();

, .

0

All Articles