wpdb::get_var() WordPress Method

The wpdb::get_var() method is a quick and easy way to run a SQL query and get a single value back from the database. This is useful for cases where you need to retrieve a single piece of data, such as a count or an average.

wpdb::get_var( string|null $query = null, int $x, int $y ) #

Retrieves one variable from the database.


Description

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


Top ↑

Parameters

$query

(string|null)(Optional) SQL query. Defaults to null, use the result from the previous query.

Default value: null

$x

(int)(Optional) Column of value to return. Indexed from 0.

$y

(int)(Optional) Row of value to return. Indexed from 0.


Top ↑

Return

(string|null) Database query result (as string), or null on failure.


Top ↑

Source

File: wp-includes/wp-db.php

	public function get_var( $query = null, $x = 0, $y = 0 ) {
		$this->func_call = "\$db->get_var(\"$query\", $x, $y)";

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

			$this->query( $query );
		}

		// Extract var out of cached results based on x,y vals.
		if ( ! empty( $this->last_result[ $y ] ) ) {
			$values = array_values( get_object_vars( $this->last_result[ $y ] ) );
		}

		// If there is a value return it, else return null.
		return ( isset( $values[ $x ] ) && '' !== $values[ $x ] ) ? $values[ $x ] : null;
	}


Top ↑

Changelog

Changelog
VersionDescription
0.71Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.