wpdb::get_results()publicWP 0.71

Gets all data of the specified query (all rows and columns). The result is returned as an array. Each element of the array is an object with data of a separate row of the table.

Method of the class: wpdb{}

No Hooks.

Returns

Array|Object|null. The result of the database query. Will return:

  • Array of objects — when $output = OBJECT or OBJECT_K.
  • Array of arrays — when $output = ARRAY_A or ARRAY_N.
  • array() — when no rows are found for the query or there is a query error.
  • NULL — when the query is an empty string or an incorrect output type ($output_type is passed).

Usage

global $wpdb;
$wpdb->get_results( $query, $output );
$query(string)

The query to be executed.

This parameter can be set to null, then the function will return the result of the last query that was executed.

Default: null

$output(constant/string)

A flag indicating in what form the data should be returned. There are 4 options:

  • OBJECT — will return an array of objects with numeric keys - the elements of the array will be objects of the table rows — [ 0 => object ].
  • OBJECT_K — similar to the previous one, only the indices of the main array will be the values of the first column of the query result — [ 'field' => object ].
    Note that if the same values enter the index, the data will be overwritten.
  • ARRAY_N — will return a numeric array, each element of which will also be a numeric array — [ 0 => [...] ].
  • ARRAY_A — will return a numeric array, each element of which will be an associative array, where the key will be the column name — [ 'field' => [...] ].

Default: OBJECT

Examples

1

#1 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;
?>
0

#2 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;
}
0

#3 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 );
0

#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.

wpdb::get_results() code WP 6.9.1

public function get_results( $query = null, $output = OBJECT ) {
	$this->func_call = "\$db->get_results(\"$query\", $output)";

	if ( $query ) {
		if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
			$this->check_current_query = false;
		}

		$this->query( $query );
	} else {
		return null;
	}

	$new_array = array();
	if ( OBJECT === $output ) {
		// Return an integer-keyed array of row objects.
		return $this->last_result;
	} elseif ( OBJECT_K === $output ) {
		/*
		 * Return an array of row objects with keys from column 1.
		 * (Duplicates are discarded.)
		 */
		if ( $this->last_result ) {
			foreach ( $this->last_result as $row ) {
				$var_by_ref = get_object_vars( $row );
				$key        = array_shift( $var_by_ref );
				if ( ! isset( $new_array[ $key ] ) ) {
					$new_array[ $key ] = $row;
				}
			}
		}
		return $new_array;
	} elseif ( ARRAY_A === $output || ARRAY_N === $output ) {
		// Return an integer-keyed array of...
		if ( $this->last_result ) {
			if ( ARRAY_N === $output ) {
				foreach ( (array) $this->last_result as $row ) {
					// ...integer-keyed row arrays.
					$new_array[] = array_values( get_object_vars( $row ) );
				}
			} else {
				foreach ( (array) $this->last_result as $row ) {
					// ...column name-keyed row arrays.
					$new_array[] = get_object_vars( $row );
				}
			}
		}
		return $new_array;
	} elseif ( strtoupper( $output ) === OBJECT ) {
		// Back compat for OBJECT being previously case-insensitive.
		return $this->last_result;
	}
	return null;
}