0

I have created a table in my WordPress database. Now, WordPress gets all its data about different posts and pages from the database. This means that WordPress always connects to database automatically without theme developers writing any code.

I want to get information from a table I added to the database inside the header.php file of my theme. My question is do I need to create a WordPress database connection by loading all the files like

require_once(__DIR__."/../wp-load.php");
require_once(__DIR__."/../wp-config.php");

$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

Or I can use the existing database connection. If I can use the existing database connection, how do I do that?

Thanks.

2 Answers 2

1

You can (and should) use the existing database connection by accessing global $wpdb. The simplest way to use it is with the get_results() method:

global $wpdb;
$results = $wpdb->get_results( 'SELECT * FROM my_table' );

There's other methods available, and things you need to consider like preparing queries and using the correct table prefix (if your table has one). An overview for all this is available in the Codex, and you'll find many helpful guides if you search Google for "wpdb".

0

If you want to make calls to tables inside your Wordpress installation, you should always use the $wpdb class.

https://codex.wordpress.org/Class_Reference/wpdb

This link shows some good examples of how to run queries to get data from tables within your Wordpress installation.

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.