Search code examples
phpkohanakohana-3kohana-db

How can I use an Alternate DB connection in Kohana 3.1


If a run the following bit of code from a Kohana 3.1 controller

$query = DB::select("select * from foo");
$results = $query->execute();
foreach($results as $result)
{
    var_dump($result);
}

Kohana will attempt to connect to the database using information from the array returned by application/config/database.php. Specifically, if will use the information set in the default group.

return array
(
    'default' => array
    (
        'type'       => 'mysql',
        'connection' => array(
            /**
             * The following options are available for MySQL:
             *
             * string   hostname     server hostname, or socket
             * string   database     database name
             * string   username     database username
             * string   password     database password
             * boolean  persistent   use persistent connections?
             *
             * Ports and sockets may be appended to the hostname.
             */
            'hostname'   => 'localhost',
            'database'   => 'kohana',
            'username'   => FALSE,
            'password'   => FALSE,
            'persistent' => FALSE,

However, this configuration array accepts multiple top level items (called db-groups, I think). How can/should I tell Kohona 3.1 to make a connection and query using information that's set in a non-default db-group.


Solution

  • You can pass a database group as an argument of execute

    Check out the source code: Line 201 of classes/kohana/database/query.php and Database::instance()

    $this->execute('group');
    

    You could also write a query starting with $query = Database::instance('group')