$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...
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.
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.
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;
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With