wpdb::get_col( string|null $query = null, int $x ): array

Retrieves one column from the database.


Description

Executes a SQL query and returns the column from the SQL result.
If the SQL result contains more than one column, the column specified is returned.
If $query is null, the specified column from the previous SQL result is returned.


Top ↑

Parameters

$query string|null Optional
SQL query. Defaults to previous query.

Default: null

$x int Optional
Column to return. Indexed from 0.

Top ↑

Return

array Database query result. Array indexed from 0 by SQL result row number.


Top ↑

Source

File: wp-includes/class-wpdb.php. View all references

public function get_col( $query = null, $x = 0 ) {
	if ( $query ) {
		if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
			$this->check_current_query = false;
		}

		$this->query( $query );
	}

	$new_array = array();
	// Extract the column values.
	if ( $this->last_result ) {
		for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
			$new_array[ $i ] = $this->get_var( null, $x, $i );
		}
	}
	return $new_array;
}


Top ↑

Changelog

Changelog
Version Description
0.71 Introduced.

Top ↑

User Contributed Notes

  1. Skip to note 1 content
    Contributed by Big-Erny
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'some_custom_table_name';
    
    $field_name = 'some_field';
    $user_id = get_current_user_id();
    
    $prepared_statement = $wpdb->prepare( "SELECT {$field_name} FROM {$table_name} WHERE  user_id = %d", $user_id );
    $values = $wpdb->get_col( $prepared_statement );

    Returns an array of $field_name values in the $table_name that match the $user_id

You must log in before being able to contribute a note or feedback.