Codex tools: Log in / create account
WordPress provides a class of functions for all database manipulations. The class is called wpdb and is based on the ezSQL class written and maintained by Justin Vincent. Though the WordPress class is slightly different than the ezSQL class, their use is essentially the same. Please see the ezSQL documentation for more information.
Within PHP code blocks in a template the $wpdb class should work as expected, but in the case of a plugin or external script it may be necessary to scope it to global before calling it in your code. This is briefly explained in the Writing a Plugin documentation.
The query function allows you to execute any query on the WordPress database. It is best to use a more specific function, however, for SELECT queries.
<?php $wpdb->query('query'); ?>
If there are any query results, the function will return an integer corresponding to the number of rows affected and the query results will cached for use by other wpdb functions. If there are no results, the function will return (int) 0. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===).
Note: It is advisable to use the wpdb->escape($user_entered_data_string) method to protect the database against SQL injection attacks by malformed or malicious data, especially when using the INSERT or UPDATE SQL commands on user-entered data in the database. See the section entitled "Escape for SQL Queries" below.
Additionally, if you wish to access the database from your code file which is not placed inside one of the standard plugin locations, you will need to include_once() the wp-db.php file as well as the wp-config.php file. Including only the wp-db.php file will not set the database connection information resulting in an error message like "Wordpress could not connect to the database".
It is always advisable to put your functionality inside a plugin. However, if you need it in some cases, this workaround is available.
For example, this is the code in a file has_great_code.php in the root/installation directory :
include_once('wp-config.php');
include_once('wp-includes/wp-db.php');
Add Post 13 to Category 2:
$wpdb->query("
INSERT INTO $wpdb->post2cat (post_id, category_id)
VALUES (13, 2)");
Delete the 'gargle' meta key and value from Post 13.
$wpdb->query("
DELETE FROM $wpdb->postmeta WHERE post_id = '13'
AND meta_key = 'gargle'");
Performed in WordPress by delete_post_meta().
Set the parent of Page 15 to Page 7.
$wpdb->query("
UPDATE $wpdb->posts SET post_parent = 7
WHERE ID = 15 AND post_status = 'static'");
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 the name of Category 4.
$name = $wpdb->get_var("SELECT cat_name FROM $wpdb->categories WHERE cat_ID=4");
echo $name;
Retrieve and display the number of users.
<?php
$user_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->users;");?>
<p><?php echo 'user count is ' . $user_count; ?></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 numbered 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.
<?php $wpdb->get_row('query', output_type, row_offset); ?>
null will return the specified row from the cached results of the previous query.
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 all of the columns from the $wpdb->links table).
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 numbered array:
echo $mylink[1]; // prints "10"
To SELECT a column, use get_col. This function outputs a 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.
<?php $wpdb->get_col('query',column_offset); ?>
null will return the specified column from the cached results of the previous query.
Get all the Categories to which Post 103 belongs.
$postcats = $wpdb->get_col("SELECT category_id
FROM $wpdb->post2cat
WHERE post_id = 103
ORDER BY category_id");
Performed in WordPress by wp_get_post_cats().
Generic, mulitple 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.
<?php $wpdb->get_results('query', output_type); ?>
null will return the data from the cached results of the previous query.
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;
}
Using the OBJECT output_type, get the 5 most recent posts in Categories 3,20, and 21 and display the permalink title to each post. (example works at WordPress Version 2.2.1)
<?php
$querystr ="
SELECT $wpdb->posts.* FROM $wpdb->posts
LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id)
WHERE $wpdb->posts.post_status = 'publish'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->post2cat.category_id IN (3,20,21)
ORDER BY $wpdb->posts.post_date DESC
LIMIT 5";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
<?php if ($pageposts): ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
<h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
<?php the_title(); ?></a></h2>
<?php endforeach; ?>
<?php else : ?>
<h2> Not Found</h2>
<?php endif; ?>
If you're making a SQL query, make sure any untrusted data is escaped properly first. This can be conveniently done with the escape method.
Note that values taken from $_GET, $_POST, $_REQUEST, $_COOKIE and $_SERVER will already be escaped, regardless of the server's magic_quotes setting.
<?php $safe_string = $wpdb->escape($unsafe_string); ?>
Note that you may need to use PHP's stripslashes() when loading the escaped data back into WordPress.
Add Meta key => value pair "Harriet's Adages" => "WordPress' database interface is like Sunday Morning: Easy." to Post 10.
$metakey = $wpdb->escape("Harriet's Adages");
$metavalue = $wpdb->escape("WordPress' database interface is like Sunday Morning: Easy.");
$wpdb->query("
INSERT INTO $wpdb->postmeta
(post_id,meta_key,meta_value)
VALUES ('10','$metakey','$metavalue')");
Performed in WordPress by add_meta().
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(); ?>
You can retrieve information about the columns of themost 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.
The WordPress database tables are easily referenced in the wpdb class.