Plastika
Plastika

Reputation: 223

php - counting number of values in an array

I currently trying to do a count of how many properties are within a particular price range and the query I am running returns only a value of 1. Obviously I am doing something wrong - and it doesn't help being not so MySQL/PhP savvy.. would anyone mind lending a hand please?

Query is below:

    $apart = $wpdb->get_var("SELECT m1.post_id
    FROM hj_postmeta m1
    INNER JOIN hj_postmeta m2 ON m1.post_id = m2.post_id
    WHERE m1.meta_key = 'price'
    AND m1.meta_value
    BETWEEN 50000 AND 74999 AND m2.meta_key = 'property_type'
    AND m2.meta_value = 'apartment'");

$apartprice = count($apart); 

Many thanks in advance.

Upvotes: 0

Views: 175

Answers (2)

hakre
hakre

Reputation: 198217

As long as you are straight forward interested in the number of rows:

$apart = $wpdb->get_var("....");
$apartprice = $wpdb->num_rows;

However I think Mihai Iorga's answer raises two very fair points in case you need to fetch all the data or the (as commented above by juergen d as well) count in the database if you do not actually process the resultset next to that one variable.

Upvotes: 1

Mihai Iorga
Mihai Iorga

Reputation: 39724

Use get_results as get_var function returns a single variable from the database:

$apart = $wpdb->get_results("SELECT m1.post_id
    FROM hj_postmeta m1
    INNER JOIN hj_postmeta m2 ON m1.post_id = m2.post_id
    WHERE m1.meta_key = 'price'
    AND m1.meta_value
    BETWEEN 50000 AND 74999 AND m2.meta_key = 'property_type'
    AND m2.meta_value = 'apartment'");

$apartprice = count($apart); 

or COUNT all with get_var:

$apart = $wpdb->get_var("SELECT COUNT(m1.post_id)
    FROM hj_postmeta m1
    INNER JOIN hj_postmeta m2 ON m1.post_id = m2.post_id
    WHERE m1.meta_key = 'price'
    AND m1.meta_value
    BETWEEN 50000 AND 74999 AND m2.meta_key = 'property_type'
    AND m2.meta_value = 'apartment'");

$apartprice = $apart;

Upvotes: 4

Related Questions