Getting WordPress database name/username/password with PHP Getting WordPress database name/username/password with PHP wordpress wordpress

Getting WordPress database name/username/password with PHP


Yes, they are defined in wp-config.php

  1. Database Name: DB_NAME
  2. Database User: DB_USER
  3. Database password: DB_PASSWORD
  4. Database Host: DB_HOST

They are define. See you wp-config.php in the root directory of Wordpress


Wordpress has some fairly goofy stuff going on throughout its OO code, this isn't the first one I've encountered as we dig deeper into the internals with each successive project at Moxune. See WP_User::__set doesn't persist custom fields as it claims.

The goofiness I refer to here of course is that something like the table prefix, aka wpdb::prefix is a public member variable, however things like dbname, dbpassword, and dbhost are protected and there are no public accessor methods.

I'm sure one of the Wordpress core devs will try to argue some rationale for it, but in the meantime may as well use some good 'ol OO to cope. My suggestion, a decorator.

class SaneDb{    private $_oDb;    public function __construct(wpdb $oDb)    {        $this->_oDb = $oDb;    }    public function __get($sField)    {        if($sField != '_oDb')            return $this->_oDb->$sField;    }    public function __set($sField, $mValue)    {        if($sField != '_oDb')            $this->_oDb->$sField = $mValue;    }    public function __call($sMethod, array $aArgs)    {        return call_user_func_array(array($this->_oDb, $sMethod), $aArgs);    }    public function getDbName() { return $this->_oDb->dbname;     }    public function getDbPass() { return $this->_oDb->dbpassword; }    public function getDbHost() { return $this->_oDb->dbhost;     }}

Then atop your plugin code (functions.php) setup a global in similar vein to wpdb.

global $sanedb;$sanedb = new SaneDb($wpdb);

From there, just use $sanedb within your plugin instead of $wpdb.

Lastly, getting ahold of the database name et al.

$sanedb->getDbName();