I’m trying to make a very simple widget that access tables contained within the same database instance as my WordPress database, but are not wordpress tables. I’m using the wpdb class according to the codex. I’m not getting any errors, but I’m also not getting any results.

Am I using the object appropriately? Or should I be rolling my own access class for my own tables?

Here is the widget code:

function widget ($args,$instance) 
{
        extract($args);

        global $wpdb;

        $title = $instance['title'];
        $catid = $instance['catid'];

        $current_user = wp_get_current_user();

        $sql="SELECT max(ID) as MaxID, status FROM Clients WHERE UserID = ".$current_user->ID;
        $clientRow = $wpdb->get_results($sql);

        $out="<div style="text-align: center; border: solid 1px Navy; background-color: #E4E4E4">";
        $out .= '<span>Client status: '.$clientRow->status.'</span></div>';

        echo $before_widget;
        echo $before_title.$title.$after_title;
        echo $out;
        echo $after_widget;
}

Thanks in advance.

3 Answers
3

If you really just want a single row, use $wpdb->get_row($sql) instead.

But your query looks funny…it looks like you’re trying to get the latest ‘client status’ for the user in which case your query should be:
'SELECT status FROM Clients WHERE UserID = '.$current_user->ID.' ORDER BY ID DESC LIMIT 1'.

And if you do that, you can then even use $status = $wpdb->get_var($sql);.

Lastly…did you consider using add_user_meta/get_user_meta instead? There’s a lot of benefits to using the native tables and functions, such as that the records get cleaned up when you delete the user and the likes.

Leave a Reply

Your email address will not be published. Required fields are marked *