Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

$wpdb->get_results() returns multiple rows as an array of objects (or an array of arrays, depending on the $output parameter). What you want is $wpdb->get_row().

Your results will come back as an array of objects, not a singular object..

This line treats the result as an object.

$clientRow->status

When in fact you've got an array with objects, this would reference the first.

$clientRow[0]->status

Not sure quite what you're expecting from the result, so hopefully the above info is enough to help fix the problem?

Small note, you may not need this..

$current_user = wp_get_current_user();

Giving $current_user scope should be enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top