Pippins Plugins
  • Email
  • Facebook
  • Feedburner
  • Github
  • Google
  • Twitter
  • Vimeo
  • Youtube
  • Rss
  • About
  • News
  • Join the Site
    • Member Benefits
    • Member Plugins
    • Email Notifications
  • Plugin Store
    • Affiliate Area
    • Checkout
  • Plugins
    • Plugin Portfolio
      • Plugin Portfolio – List View
    • Free
    • Premium
    • Member Plugins
    • Coding Standards
    • Get Plugin Support
  • Tutorials
    • Series
      • Plugin Development 101
      • Creating a User Follow System Plugin
      • Customizing Restrict Content Pro
      • Displaying Content with Easy Content Types
      • Writing Your First WordPress Plugins, Basic to Advanced
      • Working with Widgets
      • User Submitted Image Galleries
      • Plugin Thoughts
      • Integrating Stripe.com with WordPress
      • WordPress Rewrite API
    • Member Exclusive
      • Free Members
      • Subscriber Only
    • Difficulty
      • Beginner
      • Intermediate
      • Advanced
    • Action and Filter Hooks
    • Ajax
    • Custom Post Types
    • External APIs
    • Short Codes
    • Taxonomies
    • Video Tutorials
    • Widget Tutorials
    • WordPress Admin / Dashboard
    • Working with jQuery
    • WordPress Database
    • Writing Plugins
    • Tag Index
  • Reviews
  • Support Forum
  • Contact
    • Support the Site
    • Request Code Review
    • Plugin Support

Create Database Tables When Plugin is Activated

Posted on August 19, 2011 by Pippin in Intermediate, Quick Tips, Tutorials, WordPress Database, Writing Plugins 13 Comments
Home» Tutorials » Intermediate » Create Database Tables When Plugin is Activated
Tweet
Love It - 0

Using custom database tables for your WordPress plugins is one of the way that you can greatly improve the kind of plugins you are able to create. DB tables give you a way to manage, organize, and save data for your plugin, and creating them for your plugin is very simple.

This is a quick tip. Check out more Quick Tips

The following code can be placed in your main plugin file. The function, which will create the necessary database tables only if they don’t already exist, will be run when the plugin is activated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$your_db_name = $wpdb->prefix . 'your_db_name';
 
// function to create the DB / Options / Defaults					
function your_plugin_options_install() {
   	global $wpdb;
  	global $your_db_name;
 
	// create the ECPT metabox database table
	if($wpdb->get_var("show tables like '$your_db_name'") != $your_db_name) 
	{
		$sql = "CREATE TABLE " . $your_db_name . " (
		`id` mediumint(9) NOT NULL AUTO_INCREMENT,
		`field_1` mediumtext NOT NULL,
		`field_2` tinytext NOT NULL,
		`field_3` tinytext NOT NULL,
		`field_4` tinytext NOT NULL,
		UNIQUE KEY id (id)
		);";
 
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);
	}
 
}
// run the install scripts upon plugin activation
register_activation_hook(__FILE__,'your_plugin_options_install');
Tweet Follow @pippinsplugins
database, plugin, tools

13 comments on “Create Database Tables When Plugin is Activated”

  1. Zack says:
    August 19, 2011 at 4:33 pm

    Any tips on debugging this? I cannot tell you how many times I’ve tried adding a table in this manner only to get the dreaded “You have X character of unexpected output…” The best way I’ve found to debug this was to call var_dump in the core (cannot remember where at the moment). Wondering if you have any tips to make this go better.

    Reply
    • Pippin says:
      August 19, 2011 at 4:52 pm

      @Zach – I don’t have any particular tips. Using var_dump does work well. If you do it the way I’ve described here, you shouldn’t get the “X char” error.

  2. Zack says:
    August 19, 2011 at 7:12 pm

    Absolutely…I use the same technique, but since dbDelta is so picky you some times get weird errors. My favorite is when the SQL executes just fine when you directly query it, but running it through dbDelta chokes.

    Reply
  3. Create Database Tables When Plugin is Activated | Pippin’s Plugins | WpMash - WordPress News says:
    August 22, 2011 at 11:08 am

    [...] here: Create Database Tables When Plugin is Activated | Pippin’s Plugins Posted in WordPress Plugins « 40 Free And Premium WP Themes Ideal For Portfolios 10 Best [...]

    Reply
  4. Dave Navarro says:
    February 7, 2013 at 4:27 am

    What about deleting tables when your plugin is removed?

    Reply
    • Pippin says:
      February 9, 2013 at 6:36 pm

      Take a look at the uninstall hook: http://codex.wordpress.org/Function_Reference/register_uninstall_hook

  5. Danijel says:
    April 2, 2013 at 9:55 pm

    Ok wpdb->insert is not working for me at all.
    I’m using it through the ajax so can that be related to my problem. Every other thing i saw on the internet doesn’t help me at all, and all the things are correct checked everything milion times.
    Ok let me know if you can help me

    Reply
  6. ghada darraj says:
    April 17, 2013 at 4:36 pm

    thanks for that, some way it helps, but still didn’t cover my question about this :(

    -I’m trying to connect my DB to my code which I have it already in plugin, to execute a simple PHP code for viewing data form my DB such as name, description, price and the most important “IMAGES”

    -I followed your tutorial about “writing you first plugin…” and I got it very well, put I have a question ,, can I replace “single OR singular” by something means like that … if post (or page) = to NAME_OF_POST3 ,, any name that we have created it using dashboard

    Reply
    • Pippin says:
      April 17, 2013 at 7:03 pm

      I’m not sure I understand your question, sorry. Can you rephrase it?

  7. ghada darraj says:
    April 18, 2013 at 9:48 am

    okay

    I know about writing plugin,, I wrote one to save a twitter url from the setting which I write it, to show the Twitter info.after the content of pages and posts.. (I was followed you tutorial)

    Now I want to write a plugin to be show in the site page ,, which contain photos (as table of photos) and brief info. About each photo, and then user can click on it and see more detail about it , then add to cart it if they want to buy (that item) …. then go to the payment page and pay ,,,
    hint: the admin is the one who is gonna add the items info such as(upload photo, discription and price and name ) then it gonna show in the menu…..

    I’ve done this before … but in regular a theme, how can I use my codes and do some changes to them to be active in WordPress theme

    Reply
  8. ghada darraj says:
    April 18, 2013 at 9:59 am

    my fingers confused a little bit in typing,, I am sorry about that

    I want to write a plugin to be shown in the site page for example if I have a page called E-menu ,, how can I determine this thing cause I don’t want it to be in all pages, or all post, by using sing/singular…

    Reply
    • Pippin says:
      April 18, 2013 at 3:33 pm

      There’s no difference in writing this as a plugin than there is in writing it as a theme. The code is identical, just in a different location.

  9. ghada darraj says:
    April 18, 2013 at 4:35 pm

    you mean that, I can to create my pages inside the “theme folder” which I have it in “wp-content”
    And I can determine where I would like to show that page?
    such as: sing up, menu item for sell, register page, payment page,, ?

    a quick question also, how can I add “log in” above the header,, I know I have to “log in” link automatically down in within the footer,, how can I change that

    (I hope to find answers from you) cause I spent weeks to figure out the answers.. andI have no time to finish my task… please help >.<"

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Login

Lost your password?

Please enter your username or e-mail address. You will receive a new password via e-mail.

  • Facebook Become a Fan Like

  • Twitter Subscribe on Twitter Follow

  • YouTube Follow my Videos Subscribe

  • RSS Feed Subscribe with RSS Subscribe

Easy Digital Downloads

Most Loved

  • Love It Pro for WordPress
  • Write a “Love It” Plugin with Ajax to Let Users Love Their Favorite Posts / Pages
  • Simple Notices Pro Plugin for WordPress
  • User Bookmarks for WordPress
  • Front End Registration and Login Forms Plugin

Similar Plugins and Posts

  • Structuring Your First WordPress Plugin
  • How to Begin Writing Your First WordPress plugin
  • Customize Plugin Action Links
  • Sugar FAQs – WordPress FAQs Management
  • Retrieve Registered Users From the Database

Latest Premium Content

  • Plugin Development 101 – Introduction to Adding Dashboard Menus
  • Plugin Development 101 – Intro to Loading Scripts and Styles
  • User Follow System – Part 5
  • Plugin Development 101 – Intro to Short Codes
  • Plugin Development 101 – Registering a Custom Post Type
  • Plugin Development 101 – Intro to Actions

Latest Tutorials

  • Submitting Your First Pull Request to a WordPress Plugin on Github (2)

    Github is an extremely popular tool for managing WordPress plugins, and one...

  • Plugin Development 101 – Introduction to Adding Dashboard Menus (1)

    Adding new menus, both top level and sub level, to the WordPress Dashboard is a really common task for plugins...

  • Plugin Development 101 – Intro to Loading Scripts and Styles (16)

    In this part of Plugin...

Enter your email to receive automated updates when new posts are published

Latest Tweets

  • Shipped some serious code tonight, and now to hit the sack. https://t.co/1V68FVHYWg
    May 21, 2013
  • @tnorthcutt https://t.co/AuWTLzmqOY
    May 21, 2013
  • @tnorthcutt Figured it out, thanks
    May 21, 2013

Topics

meta box campaign monitor hook add_shortcode wp_enqueue_script Rémi Corson featured Tom McFarlin shortcodes attachments get_user_meta register_setting add_options_page Related posts authors mail chimp attachment plugin image forms short codes do_action login bbpress apply_filters recent posts comments post types taxonomies short code custom post type Ajax gallery images Stripe jquery taxonomy widgets users add_filter add_action easy content types widget restrict content pro easy digital downloads

Weekly Newsletter

Useful Links

  • Join the Site
  • Plugin Store
  • Affiliate Area
  • Tag Index
  • Support the Site
  • Suggest a Tutorial
  • Random Post
  • Contact

Monthly Archives

(c) 2011 Pippin's Plugins