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
$column07a = $_POST[$attributes[8]]; **<-** echo displayed **24253** $queryColumn07 = $wpdb->prepare( " SELECT DISTINCT p.id FROM plz p LEFT JOIN vermieter v ON v.id_plz=p.id WHERE p.postleitzahl='$column07a' " );` $column07 = $wpdb->query( $queryColumn07 ); **<-** echo displayed **1**
In SQL
SELECT DISTINCT p.id FROM plz p LEFT JOIN vermieter v ON v.id_plz=p.id WHERE p.postleitzahl='24253';
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:
$column07 = $wpdb->query( $queryColumn07 );
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:
$column07 = $wpdb->get_var( $queryColumn07 ); echo $column07; // Should output 3 according to your comments.