I’m using the mysql GREATEST() function to compare two table fields and display in a loop either one with the highest integer value. The 2 fields consist of vote scores for posts: UP or DOWN.
function vote_results($post_id) {
global $wpdb;
$table = $wpdb->prefix . "post_votes";
$results = $wpdb->get_row( "SELECT GREATEST (up, down) FROM $table WHERE voted_post_id = $post_id" );
echo $results->up; //echo if highest value
echo $results->down; //echo if highest value
}
Then in my loop I call the function but get Notice: Undefined property: stdClass::$up
for
echo $results->up;
and the same notice for down
. I’m not sure what I’m doing wrong here.
I think you want to use
get_var()
, notget_row()
– looking at the documentation, MySQL’sGREATEST
just returns a single value.$results
will then just be the value of the greatest (be itup
ordown
).If you want the greatest
up
and the greatestdown
, use;Agreeing with TheDeadMedic… If you use GREATEST(), please do yourself a favor by knowing what you’re doing. It returns a bigint when fed ints, and your query doesn’t give the resulting column any name. So $wpdb will obviously complain when you try to access a column which is not available. 🙂
I believe you’re seeking this: