5

I want to get WordPress database name. I have also try to get database name from $wpdb but failed. When print the $wpdb it give an object array but i don't know how to get database name from object array.

7

To get the db name using $wpdb:

global $wpdb;
echo $wpdb->dbname;

It will return database name as a string.

4
  • $wpdb->dbname is a protected property: you shouldn't read it. Use DB_NAME constant instead, as @chittaranjan suggested. Feb 26 '16 at 11:26
  • @AndreaSciamanna what is wrong using $wpdb->dbname? Would you please care to explain? That will be helpful. Feb 26 '16 at 15:10
  • This is wrong answer! To use from $dbname you should call if at first by global $dbname. Then no need to wpdb(it's wrong to use wpdb). Just use $dbname. But the better approach is DB_NAME constant. Feb 7 '17 at 10:34
  • The constant DB_NAME is not always defined - when the HyperDB plugin is in use (replaces WPDB class to support multiple databases), then having a single DB_NAME constant wouldn't make sense
    – abhij89
    Apr 8 at 11:32
6

You can also get the database name from the constant DB_NAME without going for $wpdb.

3
  • This is best answer.
    – ahmetlutfu
    Jun 2 '14 at 9:38
  • what scope do you need to be in, or what library or object do you need to load in order for DB_NAME to be recognized, and not be an uninitialized constant?
    – ahnbizcad
    Sep 13 '15 at 23:33
  • The constant DB_NAME is not always defined - when the HyperDB plugin is in use (replaces WPDB class to support multiple databases), then having a single DB_NAME constant wouldn't make sense
    – abhij89
    Apr 8 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.