Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get database name in PDO?

Tags:

database

php

pdo

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

Is there a function or constant within PDO that stores the database name (the testdb value) ? I did a var_dump on $dbh and cant find anything...

like image 227
thelolcat Avatar asked Feb 17 '12 03:02

thelolcat


People also ask

How to Get the db name in PHP?

You could use the setAttribute() (essentially a key value pair) method to store the database name when you set it up initially, then use the getAttribute() later in your code to see what the value is.

What is DSN PHP?

dsn. The Data Source Name, or DSN, contains the information required to connect to the database. In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.


2 Answers

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();
like image 82
Marc B Avatar answered Oct 14 '22 17:10

Marc B


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;
    }

    ...
like image 30
zerkms Avatar answered Oct 14 '22 19:10

zerkms