7

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.

2 Answers 2

9

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. Commented Feb 26, 2016 at 11:26
  • @AndreaSciamanna what is wrong using $wpdb->dbname? Would you please care to explain? That will be helpful. Commented Feb 26, 2016 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. Commented Feb 7, 2017 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
    Commented Apr 8, 2021 at 11:32
7

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

3
  • This is best answer.
    – ahmetlutfu
    Commented Jun 2, 2014 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
    Commented Sep 13, 2015 at 23:33
  • 1
    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
    Commented Apr 8, 2021 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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