wpdb::get_results()
Retrieves an entire SQL result set from the database (i.e., many rows).
Executes a SQL query and returns the entire SQL result.
Method of the class: wpdb{}
No Hooks.
Return
Array|Object|null
. Database query results.
Usage
global $wpdb; $wpdb->get_results( $query, $output );
- $query(string)
- SQL query.
Default: null - $output(string)
- Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. With one of the first three, return an array of rows indexed from 0 by SQL result row number. Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object ( ->column = value ), respectively. With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded.
Default: OBJECT
Examples
#1 Get the IDs and titles of drafts whose author ID = 5 and display the posts 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; }
#2 Example of a complex query with GROUP BY (reviews in WooCommerce)
/** * Returns the results of the rating (reviews in WooCommerce) grouped by ratings * * @param int $post_id post ID * * @return array of objects, where each object is a lumped data on one of the grades */ function get_cnt_rating_reviews_one_product( $post_id ){ global $wpdb; return $wpdb->get_results( $wpdb->prepare( " SELECT COUNT(meta.meta_id) as num, meta.meta_value FROM $wpdb->comments as comments INNER JOIN $wpdb->commentmeta as meta ON comments.comment_ID = meta.comment_id WHERE comments.comment_post_ID = %d AND meta_key = 'rating' GROUP BY meta.meta_value; ", $post_id ) ); } // usage get_cnt_rating_reviews_one_product( 4350 );
#3 Display the links to the author's drafts with ID = 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="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2> <?php } else : ?> <h2> Not found</h2> <?php endif; ?>
#4 Error handling
This is how to intercept errors from get_results():
global $wpdb; $result = $wpdb->get_results( "SELECT * FROM invalid query" ); if ( $wpdb->last_error ) { echo 'wpdb error: ' . $wpdb->last_error; }
Changelog
Since 0.71 | Introduced. |