Domanda

I have this function to create two tables when I activate the plugin. Only the wp_wpt_stats table are being created and not the wp_wpt_list. I know the dbdelta is picky, but I can't see what I'm doing wrong.

global $wpt_db_version;
$wpt_db_version = "1.0";

function wpt_install() {
    global $wpdb;
    global $wpt_db_version;

    $table_add_toplist = $wpdb->prefix . 'wpt_list';
    $table_add_wptstats = $wpdb->prefix . 'wpt_stats';
    $charset_collate = $wpdb->get_charset_collate();

    //-----------------------table_one-----------------------------------
        if($wpdb->get_var('SHOW TABLES LIKE ' . $table_add_toplist) != $table_add_toplist){
      $sql_one = 'CREATE TABLE ' . $table_add_toplist . '(
          id INT(11) UNSIGNED AUTO_INCREMENT,
          link_id INT(11),
          visitor_ip VARCHAR(15)
          click_at DATETIME NOT NULL,
          site_votes INT(11),
          on_page VARCHAR(255),
          UNIQUE KEY id (id)
    ) '. $charset_collate .';';


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

    //-----------------------table_two-----------------------------------
        if($wpdb->get_var('SHOW TABLES LIKE ' . $table_add_wptstats) != $table_add_wptstats){
      $sql_two = 'CREATE TABLE ' . $table_add_wptstats . '(
          id INT(11) UNSIGNED AUTO_INCREMENT,
          link_id INT(11),
          impressions INT(11),
          inclick INT(11),
          outclick INT(11),
          PRIMARY KEY  (id)
    ) '. $charset_collate .';';

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

    add_option("wpt_db_version", $wpt_db_version );
}
register_activation_hook(__FILE__,'wpt_install');
È stato utile?

Soluzione

dbdelta demands that:

  • You must put each field on its own line in your SQL statement.
  • You must have two spaces between the words PRIMARY KEY and the definition of your primary key.
  • You must use the key word KEY rather than its synonym INDEX and you must include at least one KEY.
  • You must not use any apostrophes or backticks around field names.
  • Field types must be all lowercase.
  • SQL keywords, like CREATE TABLE and UPDATE, must be uppercase.

If we look at your call:

$sql_one = 'CREATE TABLE ' . $table_add_toplist . '(
      id INT(11) UNSIGNED AUTO_INCREMENT,
      link_id INT(11),
      visitor_ip VARCHAR(15)
      click_at DATETIME NOT NULL,
      site_votes INT(11),
      on_page VARCHAR(255),
      UNIQUE KEY id (id)
) '. $charset_collate .';';

We can see that you do not append a comma to the end of every line:

      link_id INT(11),
      visitor_ip VARCHAR(15)
      click_at DATETIME NOT NULL,

So you have invalid SQL, as visitor_ip lacks a comma at the end

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a wordpress.stackexchange
scroll top