How to get database name in PDO?

Given you're on mysql, you can do select database() to get the name of the default database.

/* @var $pdo PDO */
$pdo->query('select database()')->fetchColumn();

Nope, there is no built-in feature.

But you can extend class MyPdo extends PDO, parse and store dsn and return it by some accessor

class MyPdo extends PDO
{
    ...

    /**
     * @param string $dsnParameter
     * @param string|null $default
     * @throws RuntimeException
     * @return string|null
     */
    public function getDsnValue($dsnParameter, $default = NULL)
    {
        $pattern = sprintf('~%s=([^;]*)(?:;|$)~', preg_quote($dsnParameter, '~'));

        $result = preg_match($pattern, $this->dsn, $matches);
        if ($result === FALSE) {
            throw new RuntimeException('Regular expression matching failed unexpectedly.');
        }

        return $result ? $matches[1] : $default;
    }

    ...

Tags:

Database

Php

Pdo