0

I am creating my first ever plugin for a membership site. I have a custom table named subscription with a subscr_user_id column whose values are taken from $current_user->ID. So when a current user subscribes, a new record is inserted into the table where subscr_user_id gets the value of the current user's ID. How do I query(INSERT AND SELECT) the table from a template(I don't know of any other means to test queries)?

I have this SELECT query: Note that I have preinserted one record into table subscription with subscr_user_id = 1 which means the user is an administrator. I did that thru sql console.

//Somewhere in between the body of the template.
//This query will be used for a code that checks if a user ID is already subscribed to avoid duplicate records.
global $current_user;
global $wpdb;

$user_id = $wpdb->get_row("SELECT * FROM $wpdb->subscription WHERE subscr_user_id = $current_user->ID");

echo '<p> Current user ID is:'.$user_id->subscr_user_id. '</p>';

Before I viewed the page that uses that template, I logged in as an administrator to make sure the ID is 1. Unfortunately I didn't get any result? Could anyone also please show me a sample of INSERT statement?

3

You need to tell $wpdb what subscriptions when initializing your plugin:

$wpdb->subscriptions = $wpdb->prefix . 'subscriptions';
  • I am sorry? You mean placing that statement before the query? Because it works. It also does when I replace $wpdb-> with wp_ in the query statement. – Joann Nov 27 '10 at 12:58
  • Things like $wpdb->posts work because posts field in $wpdb object is already filled by WP. To use same form for custom tables you need to init your own field and fill it with name of table, that is what code in this answer does. – Rarst Nov 27 '10 at 13:18
0

"$wpdb->subscription" only applies if you use the same table prefix (usually wp_), otherwise just use "subscription". Is your plugin checking for the prefix and creating the table accordingly?

Otherwise I can't see anything wrong with the statement.

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.