5

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?

1
  • mysql:dbname=DBNAME;host=HOSTNAME is missing ' at end ? Commented Apr 26, 2013 at 11:23

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot, its working! Could you also tell me how to access this connection to a Model/any other class?
How would this be modified to contain 2 separate connections, would it be copy the db array and db entry in aliases and just rename them to e.g. db2?
I haven't tried it ,but I think it can be done by copying and renaming aliases
0

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

<?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 a database adapter:

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

Create a sql statetment and put in variable $sql. Now do this:

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

Hope this helps.

1 Comment

Typo there, I think, should be 'dsn' not 'dbn'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.