Is there a (better) way to access $wpdb results?

I have this:

    global $wpdb;
    $wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d);',$target_user_id);
    $result = $wpdb->get_results($wpdbp);

I want to know if the query result is 1 or 0.
But a var_dump() of $result give something like:

array (size=1)
  0 => 
    object(stdClass)[4592]
      public 'EXISTS ([some query] WHERE user_id =2)' => string '0' (length=1)

Which means I should first get element 0 of array, but then, I need to access a property which name is literally the whole query.

I yet need to test if that is even doable in php (I guess yes but I don’t remember in this language precisely), and what happens if I have multiline query …
Anyway I find that so ugly … is there a cleaned way to get query result?
Maybe there’s a way to give a name string to the query or so?


Here is what I’m trying and this isn’t even working …

$qeryAsPropertyName = substr($wpdbp,7, -strlen($wpdbp-1));
$result0 = $result[0]->$qeryAsPropertyName;

2 Answers
2

This answer explains what the OP saw with column names and how to work with that, but the real answer is to use get_var() as in Howdy_McGee’s answer.


The string you’re seeing is the column name that MySQL is using for the result, because it doesn’t have any better ideas. One way is to give it an explicit name to use instead with AS, e.g.

global $wpdb;
$wpdbp = $wpdb->prepare('SELECT EXISTS ([some query] WHERE user_id =%d) AS `exists`;',
                        $target_user_id);
$result = $wpdb->get_results($wpdbp);

then the column name will be exists, i.e.

$result = $result[0]['exists'];

However I’m surprised there isn’t a ‘execute query and return scalar’ method in $wpdb that you can use instead to just fetch a single result like this. There is a better way, but I’d missed it as I was searching for terms like ‘scalar’, bah.

Leave a Comment