I have a simple SQL query: SELECT * FROM test_table__csv_import_temp_joblist WHERE url ='https://www.example.com'

In phpMyAdmin, it works well and returns a result. In WP it returns nothing:

$sql        = "SELECT * FROM test_table__csv_import_temp_joblist WHERE url ='https://www.example.com'";
$res        = $wpdb->query( $sql );

What is the issue with my query?

$wpdb->last_query returns the right query. $wpdb->last_error returns nothing.

Many Thanks

  • Are you certain that this table is in the same database as the one WordPress is using? – Jacob Peattie Jan 15 at 15:26

Your problem is that you use query method of wpdb and if you read it’s docs:

The query function allows you to execute any SQL query on the WordPress database. It is best used when there is a need for specific, custom, or otherwise complex SQL queries. For more basic queries, such as selecting information from a table, see the other wpdb functions above such as get_results, get_var, get_row or get_col.

query  (string) The SQL query you wish to execute. This function returns an integer value indicating the number of rows affected/selected for SELECT, INSERT, DELETE, UPDATE, etc. For CREATE, ALTER, TRUNCATE and DROP SQL statements, (which affect whole tables instead of specific rows) this function returns TRUE on success. If a MySQL error is encountered, the function will return FALSE. Note that since both 0 and FALSE may be returned for row queries, you should be careful when checking the return value. Use the identity operator (===) to check for errors (e.g., false === $result), and whether any rows were affected (e.g., 0 === $result).

You’ll see that it’s not what you want.

If you want to get results of the query, you should use get_results method:

$res = $wpdb->get_results( $sql );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.