0

I have this sample code that I found online that's supposed to count the number of rows in a table. Of course... It works, but when I created my own table using phpMyAdmin... It no longer works. What am i doing wrong?

I'm also wondering whey the "wp_users" table name dosen't work, but "users" does..

My table name is "test" I've also tried "wp_test" but for some reason none of them work.

<?php

$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users");
echo "<p>User count is {$user_count}</p>";

?>

FYI, I never use forums so forgive me if i'm not doing something right.

3
  • 1
    If you have table test your query will be "SELECT COUNT(*) FROM test" Commented Aug 3, 2018 at 21:55
  • Instead of $wpdb use WordPress Codex. User Count functions : codex.wordpress.org/Function_Reference/count_users & codex.wordpress.org/Function_Reference/get_user_count Commented Aug 4, 2018 at 0:43
  • Re the users table question: $wpdb->users will insert the wp db prefix for you. Makes code more portable so specifying wp_users would actually look for $wpdb->prefix.wp_users ie in your case wp_wp_users. Commented Aug 4, 2018 at 4:32

1 Answer 1

3

Are you sure that's the table name? Usually on install WordPress prompts you to setup a table prefix so the default isn't wp_.

Additionally, you need to call the global $wpdb object so it's accessible to use:

global $wpdb;
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" );
echo "<p>User count is {$user_count}</p>";

Finally, to prevent the prefix issue you can call $wpdb->prefix:

global $wpdb;
$user_count = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}users" );

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.