Reputation: 11545
$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...
Upvotes: 28
Views: 25272
Reputation: 254896
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;
}
...
Upvotes: 14
Reputation: 360592
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();
Upvotes: 47
Reputation: 8058
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.
http://www.php.net/manual/en/pdo.setattribute.php
Upvotes: -10