wpdb::get_var PHP Method

get_var() public method

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, this function returns the value in the column and row specified. If $query is null, this function returns the value in the specified column and row from the previous SQL result.
Since: 0.71
public get_var ( string | null $query = null, integer $x, integer $y ) : string | null
$query string | null Optional. SQL query. Defaults to null, use the result from the previous query.
$x integer Optional. Column of value to return. Indexed from 0.
$y integer Optional. Row of value to return. Indexed from 0.
return string | null Database query result (as string), or null on failure
    public function get_var($query = null, $x = 0, $y = 0)
    {
        $this->func_call = "\$db->get_var(\"{$query}\", {$x}, {$y})";
        if ($query) {
            $this->query($query);
        }
        // Extract var out of cached results based 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;
    }

Usage Example

function musicmate_get_store_products($product_cnt = 1)
{
    //Connect to the OSCommerce database
    $storedatabase = new wpdb(get_option('oscimp_dbuser'), get_option('oscimp_dbpwd'), get_option('oscimp_dbname'), get_option('oscimp_dbhost'));
    $prodVal = '';
    for ($i = 0; $i < $product_cnt; $i++) {
        //Get a random product
        $product_count = 0;
        while ($product_count == 0) {
            $product_id = rand(0, 30);
            $product_count = $storedatabase->get_var("SELECT COUNT(*) FROM products WHERE products_id={$product_id} AND products_status=1");
        }
        //Get product image, name and URL
        $product_image = $storedatabase->get_var("SELECT products_image FROM products WHERE products_id={$product_id}");
        $product_name = $storedatabase->get_var("SELECT products_name FROM products_description WHERE products_id={$product_id}");
        $store_url = get_option('oscimp_store_url');
        $image_folder = get_option('oscimp_prod_img_folder');
        //Build the HTML code
        $prodVal .= '<div class="store_product">';
        $prodVal .= '<a href="' . $store_url . 'product_info.php?products_id=' . $product_id . '"><img src="' . $image_folder . $product_image . '" /></a><br />';
        $prodVal .= '<a href="' . $store_url . 'product_info.php?products_id=' . $product_id . '">' . $product_name . '</a>';
        $prodVal .= '</div>';
    }
    return $prodVal;
}
All Usage Examples Of wpdb::get_var