Home How to connect to WordPress database
Post
Cancel

How to connect to WordPress database

Connect to WordPress database using PHP and MySQL. In PHP, you can connect and modify databases in which MySQL is the most popular database system for this.

Database tables hold the data found in your website. Tables are collection of related data that consists of columns and rows. For you to be able to modify these data, you need to connect to the database. There are many ways to connect to the database and WordPress made it easier.

The wpdb class & wpdb object

Unlike in writing PHP code from scratch where you need to properly configure your database connection, WordPress provides a class called wpdb that is created upon successful installation of WordPress. This class is defined in www.yourdomain.com/wp-includes/wp-db.php.

Its primary purpose is to provide all functions needed to communicate with WordPress database.

You don’t use the wpdb class to your codes instead WordPress provides an object called $wpdb that came from wpdb class. Making a connection to the database was the primary purpose of this object.

Now, to make a connection to the database in your WordPress PHP code, you need to declare $wpdb as a global variable by using the global keyword.

You will now have a PHP code like this:

1
2
3
function myFunction() {     
  global $wpdb; 
} 

That’s it! You successfully connected to the WordPress database. From this point, you should be able to use all database functions of WordPress.

Database tables generated by WordPress is not the only tables that $wpdb can modify. It also includes the other tables generated by other means such as installing custom plugins and creating some yourselves manually.

This post is licensed under CC BY 4.0 by the author.

How to generate a random string in PHP

How to create SEO friendly URL in PHP