-1

I have a custom table within my wordpress database. I would like to COUNT the rows in the table that have the same value.

So for example:

IP ADDRESS

0.0.0.0.0

0.0.0.0.1

0.0.0.0.0

The output would then be:

there are 2 x 0.0.0.0.0

there are 1 x 0.0.0.0.1

I can achieve the above fine with a normal sql query, but i am trying to do this via the $wpdb class

Here is my query:

$table =  $wpdb->prefix . 'wplt';

$posts = $wpdb->get_results("SELECT ip_address, COUNT(ip_address) FROM $table GROUP BY ip_address");

foreach ( $posts as $post ) {

    echo $post->ip_address;

    echo $post->COUNT(ip_address);

}

With the above i get the following error:

Fatal error: Call to undefined method stdClass::COUNT()

1
  • var_dump($post) normally shows you more. You likely mean $post->{'COUNT(ip_address)'};. Commented Jul 28, 2013 at 18:27

1 Answer 1

2

This error you are getting because $post object doesn't has any count function

Fatal error: Call to undefined method stdClass::COUNT()

If you want to show the count of ip address from query you can assign an alias to that count in the query like

$table =  $wpdb->prefix . 'wplt';

$posts = $wpdb->get_results("SELECT ip_address, COUNT(ip_address) AS ip_count FROM $table GROUP BY ip_address");

foreach ( $posts as $post ) {

    echo $post->ip_address;

    echo $post->ip_count ;

}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.