wpdb::get_col_info()
Retrieves column metadata from the last query.
Method of the class: wpdb{}
Uses: wpdb::load_col_info()
No Hooks.
Return
Mixed
. Column results.
Usage
global $wpdb; $wpdb->get_col_info( $info_type, $col_offset );
- $info_type(string)
- Possible values include 'name', 'table', 'def', 'max_length', 'not_null', 'primary_key', 'multiple_key', 'unique_key', 'numeric', 'blob', 'type', 'unsigned', 'zerofill'.
Default: 'name' - $col_offset(int)
- 0: col name. 1: which table the col's in. 2: col's max length.
3: if the col is numeric. 4: col's type.
Default: -1
Examples
#1 Demo of work
Let's make a query:
global $wpdb; $results = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta" );
Now let's get the data about the table columns of this query:
$cols_data = $wpdb->get_col_info( 'name' ); /* Array ( [0] => meta_id [1] => post_id [2] => meta_key [3] => meta_value ) */ $cols_data = $wpdb->get_col_info( 'max_length' ); /* Array ( [0] => 6 [1] => 5 [2] => 45 [3] => 20205 ) */ $cols_data = $wpdb->get_col_info( 'type' ); /* Array ( [0] => 8 [1] => 8 [2] => 253 [3] => 252 ) */
What happens if you specify a column name that does not exist:
$cols_data = $wpdb->get_col_info( 'primary_key' ); /* Notice: Undefined property: stdClass::$primary_key in /wpexample.com/public_html/wp-includes/wp-db.php on line 3435 Notice: Undefined property: stdClass::$primary_key in /wpexample.com/public_html/wp-includes/wp-db.php on line 3435 Notice: Undefined property: stdClass::$primary_key in /wpexample.com/public_html/wp-includes/wp-db.php on line 3435 Notice: Undefined property: stdClass::$primary_key in /wpexample.com/public_html/wp-includes/wp-db.php on line 3435 Array ( [0] => [1] => [2] => [3] => ) */
To get the data of an individual column, you need to specify its index in the second parameter:
echo $wpdb->get_col_info( 'name', 0 ); //> meta_id echo $wpdb->get_col_info( 'name', 1 ); //> post_id echo $wpdb->get_col_info( 'max_length', 0 ); //> 6 echo $wpdb->get_col_info( 'max_length', 1 ); //> 5
Changelog
Since 0.71 | Introduced. |
wpdb::get_col_info() wpdb::get col info code WP 6.8
public function get_col_info( $info_type = 'name', $col_offset = -1 ) { $this->load_col_info(); if ( $this->col_info ) { if ( -1 === $col_offset ) { $i = 0; $new_array = array(); foreach ( (array) $this->col_info as $col ) { $new_array[ $i ] = $col->{$info_type}; ++$i; } return $new_array; } else { return $this->col_info[ $col_offset ]->{$info_type}; } } }