tags:

views:

109

answers:

2

I'm doing the following in a custom function:

    $exists = $wpdb->query($wpdb->prepare('
    SELECT COUNT(*)
    FROM wp_%d_gdsr_data_article
    WHERE post_id = %d

', $blog_id, $post_id));

$exists evaluates to 1 even if no rows are returned by the query. Also, var_dump($wpdb->queries) yields a NULL. Anyone know what is going on here?

thanks,

+1  A: 

Use $wpdb->get_var($query) instead.

Accordingly, use $wpdb->get_row() to retrieve a single row as a single object (or array), and $wpdb->get_results() to get a result set.

TheDeadMedic
Thanks but why would it return 1 when it is supposed to return a row count? Also any idea why $wpdb->queries is empty?
codecowboy
`$wpdb->query()` should only be used for executable queries, as it only returns the number of rows or false if no rows. `$wpdb->queries` is only utilised if you define `SAVEQUERIES` as true.
TheDeadMedic
+1  A: 

From the documentation:

The function returns an integer corresponding to the number of rows affected/selected. If there is a MySQL error, the function will return FALSE. (Note: since both 0 and FALSE can be returned, make sure you use the correct comparison operator: equality == vs. identicality ===).

The query returns 1 row so the query() function returns 1 - and will always return 1 for the query that you post in your question, even if the number of rows selected by the COUNT is 0. Use get_var, get_row, or get_results as suggested by TheDeadMedic to get the actual result of the query, which might be 0, 1, 2, etc.

thetaiko