Languages: English • Italiano • 日本語 Русский • 中文(简体) • 中文(繁體) • 한국어 • (Add your language)
WordPress defines a class called wpdb, which contains a set of functions used to interact with a database. Its primary purpose is to provide an interface with the WordPress database, but can be used to communicate with any other appropriate database. The class source code is loosely based on the ezSQL class; written and maintained by Justin Vincent
Warning: Methods in the wpdb()
class should not be called directly. Use the global $wpdb
object instead!
WordPress provides a global object variable, $wpdb
, which is an instantiation of the wpdb class defined in /wp-includes/wp-db.php. By default, $wpdb
is instantiated to talk to the WordPress database. To access $wpdb
in your WordPress PHP code, declare $wpdb
as a global variable using the global keyword
, or use the superglobal $GLOBALS
in the following manner:
// 1st Method - Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object global $wpdb; $results = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT ); // 2nd Method - Utilizing the $GLOBALS superglobal. Does not require global keyword ( but may not be best practice ) $results = $GLOBALS['wpdb']->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );
The $wpdb
object is not limited to the default tables created by WordPress; it can be used to read data from any table in the WordPress database (such as custom plugin tables). For example to SELECT some information from a custom table called "mytable", you can do the following.
$myrows = $wpdb->get_results( "SELECT id, name FROM mytable" );
The $wpdb
object can talk to any number of tables, but only to one database at a time; by default the WordPress database. In the rare case you need to connect to another database, you will need to instantiate your own object from the wpdb
class with your own database connection information. For extremely complicated setups with many databases, consider using hyperdb instead.
Some of the functions in this class take an SQL statement as input. You must SQL escape all untrusted values you incorporate into the SQL query to prevent SQL injection attacks. Check the documentation to see if the function you plan to use escapes SQL for you or expects it to be pre-escaped.
For more on SQL escaping in WordPress, see the section entitled Protect Queries Against SQL Injection Attacks below.
The get_var
function returns a single variable from the database. Though only one variable is returned, the entire result of the query is cached for later use. Returns NULL if no result is found.
<?php $wpdb->get_var( 'query', column_offset, row_offset ); ?>
null
will return the specified variable from the cached results of the previous query.Retrieve and display the number of users.
<?php $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" ); echo "<p>User count is {$user_count}</p>"; ?>
Retrieve and display the sum of a Custom Field value.
<?php // set the meta_key to the appropriate custom field meta key $meta_key = 'miles'; $allmiles = $wpdb->get_var( $wpdb->prepare( " SELECT sum(meta_value) FROM $wpdb->postmeta WHERE meta_key = %s ", $meta_key ) ); echo "<p>Total miles is {$allmiles}</p>"; ?>
To retrieve an entire row from a query, use get_row
. The function can return the row as an object, an associative array, or as a numerically indexed array. If more than one row is returned by the query, only the specified row is returned by the function, but all rows are cached for later use. Returns NULL if no result is found, consider this when using the returned value in arguments, see example below.
<?php $wpdb->get_row('query', output_type, row_offset); ?>
Get all the information about Link 10.
$mylink = $wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10" );
The properties of the $mylink
object are the column names of the result from the SQL query (in this example all the columns from the $wpdb->links
table, but you could also query for specific columns only).
echo $mylink->link_id; // prints "10"
In contrast, using
$mylink = $wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_A );
would result in an associative array:
echo $mylink['link_id']; // prints "10"
and
$mylink = $wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10", ARRAY_N );
would result in a numerically indexed array:
echo $mylink[1]; // prints "10"
If there is no record with ID 10 in the links table, null
will be returned. The following would then be false:
if ( null !== $mylink ) { // do something with the link return true; } else { // no link found return false; }
To SELECT a column, use get_col
. This function outputs a one dimensional array. If more than one column is returned by the query, only the specified column will be returned by the function, but the entire result is cached for later use. Returns an empty array if no result is found.
<?php $wpdb->get_col( 'query', column_offset ); ?>
null
will return the specified column from the cached results of the previous query.For this example, assume the blog is devoted to information about automobiles. Each post describes a particular car (e.g. 1969 Ford Mustang), and three Custom Fields, manufacturer, model, and year, are assigned to each post. This example will display the post titles, filtered by a particular manufacturer (Ford), and sorted by model and year.
The get_col form of the wpdb Class is used to return an array of all the post ids meeting the criteria and sorted in the correct order. Then a foreach construct is used to iterate through that array of post ids, displaying the title of each post. Note that the SQL for this example was created by Andomar.
<?php $meta_key1 = 'model'; $meta_key2 = 'year'; $meta_key3 = 'manufacturer'; $meta_key3_value = 'Ford'; $postids=$wpdb->get_col( $wpdb->prepare( " SELECT key3.post_id FROM $wpdb->postmeta key3 INNER JOIN $wpdb->postmeta key1 ON key1.post_id = key3.post_id AND key1.meta_key = %s INNER JOIN $wpdb->postmeta key2 ON key2.post_id = key3.post_id AND key2.meta_key = %s WHERE key3.meta_key = %s AND key3.meta_value = %s ORDER BY key1.meta_value, key2.meta_value ", $meta_key1, $meta_key2, $meta_key3, $meta_key3_value ) ); if ( $postids ) { echo "List of {$meta_key3_value}(s), sorted by {$meta_key1}, {$meta_key2}"; foreach ( $postids as $id ) { $post = get_post( intval( $id ) ); setup_postdata( $post ); ?> <p> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </p> <?php } } ?>
This example lists all posts that contain a particular custom field, but sorted by the value of a second custom field.
<?php // List all posts with custom field Color, sorted by the value of custom field Display_Order // does not exclude any 'post_type' // assumes each post has just one custom field for Color, and one for Display_Order $meta_key1 = 'Color'; $meta_key2 = 'Display_Order'; $postids = $wpdb->get_col( $wpdb->prepare( " SELECT key1.post_id FROM $wpdb->postmeta key1 INNER JOIN $wpdb->postmeta key2 ON key2.post_id = key1.post_id AND key2.meta_key = %s WHERE key1.meta_key = %s ORDER BY key2.meta_value+(0) ASC ", $meta_key2, $meta_key1 ) ); if ( $postids ) { echo "List of {$meta_key1} posts, sorted by {$meta_key2}"; foreach ( $postids as $id ) { $post = get_post( intval( $id ) ); setup_postdata( $post ); ?> <p> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"> <?php the_title(); ?> </a> </p> <?php } } ?>
Generic, multiple row results can be pulled from the database with get_results
. The function returns the entire query result as an array. Each element of this array corresponds to one row of the query result and, like get_row
, can be an object, an associative array, or a numbered array. If no matching rows are found, or if there is a database error, the return value will be an empty array. If your $query string is empty, or you pass an invalid $output_type, NULL will be returned.
<?php $wpdb->get_results( 'query', output_type ); ?>
Since this function uses the $wpdb->query() function all the class variables are properly set. The results count for a 'SELECT' query will be stored in $wpdb->num_rows.
Get the IDs and Titles of all the Drafts by User 5 and echo the Titles.
$fivesdrafts = $wpdb->get_results( " SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5 " ); foreach ( $fivesdrafts as $fivesdraft ) { echo $fivesdraft->post_title; }
Get all information on the Drafts by User 5.
<?php $fivesdrafts = $wpdb->get_results( " SELECT * FROM $wpdb->posts WHERE post_status = 'draft' AND post_author = 5 " ); if ( $fivesdrafts ) { foreach ( $fivesdrafts as $post ) { setup_postdata( $post ); ?> <h2> <a href="<?php the_permalink(); ?>" rel="bookmark" title="Permalink: <?php the_title(); ?>"> <?php the_title(); ?> </a> </h2> <?php } } else { ?> <h2>Not Found</h2> <?php } ?>
Insert a row into a table.
<?php $wpdb->insert( $table, $data, $format ); ?>
Possible format values: %s as string; %d as integer (whole number); and %f as float. (See below for more information.)
After insert, the ID generated for the AUTO_INCREMENT column can be accessed with:
$wpdb->insert_id
This function returns false if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1).
Please note: The value portion of the data parameter's column=>value pairs must be scalar. If you pass an array (or object) as a value to be inserted you will generate a warning similar to "mysql_real_escape_string() expects parameter 1 to be string, array given on line 880 in file /var/www/html/wp-includes/wp-db.php".
Insert two columns in a row, the first value being a string and the second a number:
$wpdb->insert( 'table', array( 'column1' => 'value1', 'column2' => 123 ), array( '%s', '%d' ) );
Replace a row in a table if it exists or insert a new row in a table if the row did not already exist.
<?php $wpdb->replace( $table, $data, $format ); ?>
Possible format values: %s as string; %d as integer (whole number); and %f as float. (See below for more information.)
If the length of a string element in the $data array parameter is longer that the defined length in the MySql database table, the insert will fail, this function will return false, but $wpdb->last_error will not be set to a descriptive message. You must ensure the data you wish to insert will fit in the database - do not assume the MySql will truncate the data.
After replace, the ID generated for the AUTO_INCREMENT column can be accessed with:
$wpdb->insert_id
This function returns a count to indicate the number of rows affected. This is the sum of the rows deleted and inserted. If the count is 1 for a single-row REPLACE, a row was inserted and no rows were deleted. If the count is greater than 1, one or more old rows were deleted before the new row was inserted. It is possible for a single row to replace more than one old row if the table contains multiple unique indexes and the new row duplicates values for different old rows in different unique indexes.
This function returns false if an existing row could not be replaced and a new row could not be inserted.
Replace a row, the first value being the row id, the second a string and the third a number:
$wpdb->replace( 'table', array( 'indexed_id' => 1, 'column1' => 'value1', 'column2' => 123 ), array( '%d', '%s', '%d' ) );
Update a row in the table. Returns false if errors, or the number of rows affected if successful.
<?php $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); ?>
Possible format values: %s as string; %d as integer (whole number) and %f as float. (See below for more information.) If omitted, all values in $where will be treated as strings.
Return values: This function returns the number of rows updated, or false if there is an error. Keep in mind that if the $data matches what is already in the database, no rows will be updated, so 0 will be returned. Because of this, you should probably check the return with false === $result
Update a row, where the ID is 1, the value in the first column is a string and the value in the second column is a number:
$wpdb->update( 'table', array( 'column1' => 'value1', // string 'column2' => 'value2' // integer (number) ), array( 'ID' => 1 ), array( '%s', // value1 '%d' // value2 ), array( '%d' ) );
Attention: %d
can't deal with comma values - if you're not using full numbers, use string/%s.
The delete function was added in WordPress 3.4.0, and can be used to delete rows from a table. The usage is very similar to update and insert. It returns the number of rows updated, or false on error.
<?php $wpdb->delete( $table, $where, $where_format = null ); ?>
// Default usage. $wpdb->delete( 'table', array( 'ID' => 1 ) ); // Using where formatting. $wpdb->delete( 'table', array( 'ID' => 1 ), array( '%d' ) );
The query
function allows you to execute any SQL query on the WordPress database. It is best used when there is a need for specific, custom, or otherwise complex SQL queries. For more basic queries, such as selecting information from a table, see the other wpdb
functions above such as get_results, get_var, get_row or get_col
.
<?php $wpdb->query('query'); ?>
This function returns an integer value indicating the number of rows affected/selected for SELECT, INSERT, DELETE, UPDATE, etc. For CREATE, ALTER, TRUNCATE and DROP SQL statements, (which affect whole tables instead of specific rows) this function returns TRUE
on success. If a MySQL error is encountered, the function will return FALSE
. Note that since both 0 and FALSE
may be returned for row queries, you should be careful when checking the return value. Use the identity operator (===) to check for errors (e.g., false === $result), and whether any rows were affected (e.g., 0 === $result).
Delete the 'gargle' meta key and value from Post 13. (We'll add the 'prepare' method to make sure we're not dealing with an illegal operation or any illegal characters):
$wpdb->query( $wpdb->prepare( " DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = %s ", 13, 'gargle' ) );
Performed in WordPress by delete_post_meta()
.
Set the parent of Page 15 to Page 7.
$wpdb->query( $wpdb->prepare( " UPDATE $wpdb->posts SET post_parent = %d WHERE ID = %d AND post_status = %s ", 7, 15, 'static' ) );
For a more complete overview of SQL escaping in WordPress, see database Data Validation. It is a must-read for all WordPress code contributors and plugin authors.
All data in SQL queries must be SQL-escaped before the SQL query is executed to prevent against SQL injection attacks. The prepare
method performs this functionality for WordPress, which supports both a sprintf()-like and vsprintf()-like syntax.
Please note: As of 3.5, wpdb::prepare() enforces a minimum of 2 arguments. [more info]
<?php $sql = $wpdb->prepare( 'query' , value_parameter[, value_parameter ... ] ); ?>
The query parameter for prepare accepts sprintf()-like placeholders. The %s (string), %d (integer) and %f (float) formats are supported. (The %s and %d placeholders have been available since the function was added to core in Version 2.3, %f has only been available since Version 3.3.) Any other %
characters may cause parsing errors unless they are escaped. All %
characters inside SQL string literals, including LIKE wildcards, must be double-% escaped as %%
. All of %d, %f, and %s are to be left unquoted in the query string. Note that the %d placeholder only accepts integers, so you can't pass numbers that have comma values via %d. If you need comma values, use %f as float instead.
Add Meta key => value pair "Harriet's Adages" => "WordPress' database interface is like Sunday Morning: Easy." to Post 10.
$metakey = "Harriet's Adages"; $metavalue = "WordPress' database interface is like Sunday Morning: Easy."; $wpdb->query( $wpdb->prepare( " INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value ) VALUES ( %d, %s, %s ) ", 10, $metakey, $metavalue ) );
Performed in WordPress by add_meta()
.
The same query using vsprintf()-like syntax.
$metakey = "Harriet's Adages"; $metavalue = "WordPress' database interface is like Sunday Morning: Easy."; $wpdb->query( $wpdb->prepare( " INSERT INTO $wpdb->postmeta ( post_id, meta_key, meta_value ) VALUES ( %d, %s, %s ) ", array( 10, $metakey, $metavalue ) ) );
Note that in this example we pack the values together in an array. This can be useful when we don't know the number of arguments we need to pass until runtime.
Notice that you do not have to worry about quoting strings. Instead of passing the variables directly into the SQL query, use a %s
placeholder for strings, a %d
placedolder for integers, and a %f as a placeholder for floats. You can pass as many values as you like, each as a new parameter in the prepare()
method.
You can turn error echoing on and off with the show_errors
and hide_errors
, respectively.
<?php $wpdb->show_errors(); ?>
<?php $wpdb->hide_errors(); ?>
You can also print the error (if any) generated by the most recent query with print_error
.
<?php $wpdb->print_error(); ?>
Note: If you are running WordPress Multisite, you must define the DIEONDBERROR constant for database errors to display like so:
<?php define( 'DIEONDBERROR', true ); ?>
You can retrieve information about the columns of the most recent query result with get_col_info
. This can be useful when a function has returned an OBJECT whose properties you don't know. The function will output the desired information from the specified column, or an array with information on all columns from the query result if no column is specified.
<?php $wpdb->get_col_info('type', offset); ?>
You can clear the SQL result cache with flush
.
<?php $wpdb->flush(); ?>
This clears $wpdb->last_result
, $wpdb->last_query
, and $wpdb->col_info
.
If you are using Multi-Site, you also have access to the following:
The WordPress database tables are easily referenced in the wpdb
class.
These tables are used only in multisite installations.
wpdb() is located in wp-includes/wp-db.php
.