If you are thinking to write a wordpress plugin or wordpress theme and want to access wordpress database in them than this wordpress post can help you in connecting to your wordpress database from your wordpress theme or plugin. I will tell you how you can execute any kind of sql query in this article. WordPress have its own class to access the wordpress database without worrying about the database connection.

What is $wpdb?

WordPress have a global object $wpdb (wordpress database) to access the wordpress database.

$wpdb methods

$wpdb have several methods that you can use to execute queries.

1) Execute any query:
use this method to execute any sql query.

<?php $wpdb->query("sql query you want to execute"); ?>

This function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE.

2) Select a signle value:
Use this method to fetch a single value from the database.

<?php $wpdb->get_var('any select query',column_offset,row_offset); ?>

column_offset : (integer) The column no. you want. Defaults is 0.
row_offset : (integer) The row no. you want. Defaults is 0.

3) Select a single row:
Use this method to fetch a single row from the wordpress database.

<?php $wpdb->get_row('any select query', output_type, row_offset); ?>

output_type
OBJECT – get_row() Method will return result in form of Object.
ARRAY_A – get_row() Method will return result in form of associative array.
ARRAY_N – get_row() Method will return result in form of numerically indexed array.
row_offset
(integer) Which row no. to return. Defaults is 0.

4) Select a single column:
Use this method to fetch a single column from the wordpress database.

<?php $wpdb->get_col('any select query', column_offset); ?>

column_offset
(integer) Which column no. to return. Defaults is 0.

5) Select a multiple rows:
Use this method to fetch a multiple rows from the wordpress database.

<?php $wpdb->get_results('any select query', output_type); ?>

output_type
OBJECT – get_results() Method will return result in form of numerically indexed array of row objects.
OBJECT_K – get_results() Method will return result in form of associative array of row objects, using first column’s values as keys.
ARRAY_A – get_results() Method will return result in form of numerically indexed array of associative arrays, using column names as keys.
ARRAY_N – get_results() Method will return result in form of numerically indexed array of numerically indexed arrays.

6) Inserting a row
This method will insert a row into the defined table of the wordpress database.

 <?php $wpdb->insert( "table name", $data); ?>

$data : An array with keys as column name and values as values.