Is it mandatory to use $wpdb->prefix in custom tables

It is mandatory, though it is not enforced. Consider the scenario when two WordPress site has been setup in the same database. One with prefix wp_ and another with wp2_. If you install your plugin in both of the sites with the prefix, your created tables will be wp_liveshoutbox for first site and wp2_liveshoutbox for … Read more

How to return number of found rows from SELECT query

If you are merely trying to get a count, $wpdb->get_var(); along with using COUNT() in your sql will be better: ### Search for IP in database function postviews_get_ip($id, $ip) { global $post, $wpdb; $rowcount = $wpdb->get_var(“SELECT COUNT(*) FROM $wpdb->wp_postviews_ips WHERE postid = $id AND ip = ‘$ip'”); return $rowcount; } postviews_get_ip($id, $_SERVER[‘REMOTE_ADDR’]); //both $id and … Read more

Showing errors with $wpdb update

I would recommend running the following code right after your query to see what’s happening: exit( var_dump( $wpdb->last_query ) ); This should print the last query that hit your database. In cases like these, I usually will manually run such a query through phpMyAdmin to see if it runs without errors and to see if … Read more

Query to sort a list by meta key first (if it exists), and show remaining posts without meta key ordered by title

Thank you everyone for your help! In the end the query below got me the results I desired – which was to show and sort the posts by a custom field of “publication_date” first – sorting by the date, and if there were multiple of the same date (say, 4 marked June 2013), it would … Read more

WPDB Insert or if exists Update

First, you are using prepare incorrectly. You seem to have $wpdb->update‘s arguments wrapped in $wpdb->prepare like that. That won’t work. In effect, you are passing update a single argument– the output of prepare. Try something simple like the following and you will see why that won’t work: $post_id = 123; $item_stock = 567; var_dump( $wpdb->prepare( … Read more