0

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.

1
  • 2
    let the DB do the counting SELECT count(m1.post_id) as count ... Commented Sep 23, 2012 at 19:30

2 Answers 2

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, +1 for a fantastic answer!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.