[ACCEPTED]-Getting WordPress database name/username/password with PHP-wordpress

Accepted answer
Score: 16

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 2 you wp-config.php in the root directory 1 of Wordpress

Score: 4

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

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

I'm sure one of the 8 Wordpress core devs will try to argue some 7 rationale for it, but in the meantime may 6 as well use some good 'ol OO to cope. My 5 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 4 code (functions.php) setup a global in similar vein to wpdb.

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

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

Lastly, getting ahold of the database 1 name et al.

$sanedb->getDbName();

More Related questions