connect to WordPress database

How to connect to WordPress database

This post has been viewed 116 times.

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 holds 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:

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.

Hello, I am a freelance website and mobile application developer. I am also the owner of this website, so if you have any projects for me you can contact me at [email protected] or use the contact page. When I’m not doing some work, I can be found watching Anime/Asian Dramas/American TV Series, playing computer games, and writing tutorials on this website. I run the program repeatedly hoping the error won’t show up next time.