use of wpdb, I cannot use $wpdb to reach my custom sql table

Hi expert,

I have been trying to use $wpdb in my custom page template, I can get the SQL query run and get the result when i search data in the default wordpress table, but it doesn't show result when i search data in the table i create myself in phpmyadmin, my own table also in the same wordpress database. below is my code.

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

experts please help my out of this, thank you so much

Ray

  • Vaughan

    Hi Ray,

    Hope you're well?

    That method only works for default WP tables, for non wp core tables you will still need to add the table name in manually and use $wpdb->prefix

    <?php
    $table_name = 'your_table';
    $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->prefix . $table_name" );
    echo "<p>User count is {$user_count}</p>";
    ?>

    You could add your table to the $wpdb object if you were distributing a plugin, but it isn't necessary for how you are using it.

    global $wpdb;
    $wpdb['your_table'] = $wpdb->prefix . 'your_table';

    Hope this helps

  • Kwok Chun

    <?php
    $table_name = 'your_table';
    $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->prefix . $table_name" );
    echo "<p>User count is {$user_count}</p>";
    ?>

    Hi Vaughan,

    thank you so much for your prompt reply.

    I tried the above code to add the prefix manually, but it still only output "User count is " but without the actual count, what is strange to me is when I use some plugin like Database browser, I can browse the data in my custom table in frontend admin panel, but when I try to use the above php code in my page template to out the data in order to perform some more custom query, I can't get the result.

    please help...thank you so much

    best regards
    Ray

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.