Skip to content
Advertisement

wpdb query gives back a wrong result

I’ve written some code in my PHP snippet which is on my WordPress page and the wpdb query gives me always a wrong result.

In WordPress

JavaScript

In SQL

JavaScript

phpmyadmin displayed 3 which is the correct result for that query

What did I do wrong? May you help me in someway?

Advertisement

Answer

The reason why you’re getting 1 as a result is because you’re using the query() method instead of get_results() or get_var().

From the $wpdb::query() documentation:

Return:

(int|bool) Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows affected/selected for all other queries. Boolean false on error.

(Emphasis mine.)

So, when you run this:

JavaScript

You get 1 because query() is returning the number of rows found by your SELECT query.

In your specific case, as pointed out earlier, you want to use get_var() instead to get the actual ID returned by the query:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement