I’m working on a voting plugin for my site and I want to create 2 tables: one that stores votes and another that stores voter ips.

In Codex it suggests to use an if statement to see if the table has already been created when installing the plugin but how can I alter the code if I’m creating 2 tables?

This is my if statement in the plugin install function, currently set to check if 1 table already exists.

...

   $table_name1 = $wpdb->prefix . "voters_ip";
   $table_name2 = $wpdb->prefix . "vote_posts";
   $installed_ver = get_option( "postvote_version" );  

   if($wpdb->get_var("show tables like '$table_name'") != $table_name1) { //unsure how to add both tables

      $sql = "CREATE TABLE " . $table_name1 . " (
      id bigint(20) NOT NULL AUTO_INCREMENT,
      vote_post_id bigint(20) NOT NULL,
      voter_ip varchar(100) NOT NULL,
      UNIQUE KEY id (id)
    );";

      $sql = "CREATE TABLE " . $table_name2 . " (
      id bigint(20) NOT NULL AUTO_INCREMENT,
      vote_post_id bigint(20) NOT NULL,
      up int(11) NOT NULL,
      ddown int(11) NOT NULL,
      UNIQUE KEY id (id)
    );";

      require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
      dbDelta($sql);

      add_option("postvote_version", $postvote_version);
   }

....

What is the correct way to check if both tables exist?

3 s
3

Basic programming techniques you should have learned before building a plugin:

  1. You can concatenate checks with && (and) and || (or).
  2. You can (and should) guard each CREATE query with its own check

SQL syntax you should have looked into before writing queries on your own:

  • IF NOT EXISTS

On a related note, please make sure that you delete these tables when the plugin is uninstalled/deleted.

PS: No offense intended, but it does look like you copy pasted without knowing what the code does. Please be aware that by doing this in a plugin you risk other people’s installations!

Leave a Reply

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