Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Wordpress $wpdb->query() response 1 when the rows returned is 0

Tags:

php

wordpress

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,

like image 831
codecowboy Avatar asked Jun 07 '10 13:06

codecowboy


People also ask

Where is Wpdb defined in WordPress?

For performing database operations WordPress provides a class wpdb which is present in the file – wp-includes\wp-db. php. This class abstracts the database functions for WordPress and most WordPress functions directly or indirectly use this class.

How do I query a database in WordPress?

Below is an example of querying the database for posts within a category using WP_Query class. $query = new WP_Query( 'cat=12' ); The result will contain all posts within that category which can then be displayed using a template. Developers can also query WordPress database directly by calling in the $wpdb class.


1 Answers

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.

like image 191
thetaiko Avatar answered Oct 14 '22 09:10

thetaiko