Should I use wpdb prepare?

It’s best practice to always use prepare but the main use of it is to prevent against SQL injection attacks, and since there is no input from the users/visitors or they can’t effect the query then that is not an issue in your current example. But like I said before it’s best practice to use … Read more

How to print the excuted sql right after its execution

The $wpdb object has some properties getting set for that: global $wpdb; // Print last SQL query string echo $wpdb->last_query; // Print last SQL query result echo $wpdb->last_result; // Print last SQL query Error echo $wpdb->last_error; Note: First of all you have to set define( ‘SAVEQUERIES’, true ); in your wp-config.php file at root folder … Read more

How do you properly prepare a %LIKE% SQL statement?

The $wpdb->esc_like function exists in WordPress because the regular database escaping does not escape % and _ characters. This means you can add them in your arguments to wpdb::prepare() without problem. This is also what I see in the core WordPress code: $wpdb->prepare(” AND $wpdb->usermeta.meta_key = ‘{$wpdb->prefix}capabilities’ AND $wpdb->usermeta.meta_value LIKE %s”, ‘%’ . $this->role . … Read more

Using wpdb to connect to a separate database

Yes it’s possible. The wpdb object can be used to access any database and query any table. Absolutely no need to be WordPress related, which is very interesting. The benefit is the ability to use all the wpdb classes and functions like get_results, etc so that there’s no need to re-invent the wheel. Here’s how: … Read more