WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] wpdb to create table is driving me nuts! Please help (4 posts)

  1. husar
    Member
    Posted 6 years ago #

    Okay, what am I doing wrong? Writing a plugin that creates a table. Here is my code but it never creates the table.

    I have other functions in the plugin that work fine.

    function myplugin_install() {
       global $wpdb;
       $table_name = $wpdb->prefix . "myplugtable";
       if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
    
          $sql = "CREATE TABLE " . $table_name . " (
    	  Title varchar(250) NOT NULL,
      		Owner varchar(256) NOT NULL,
      		Available datetime NOT NULL,
      		Status varchar(256) NOT NULL,
      		Sound varchar(256) NOT NULL,
      		Versions int(11) NOT NULL,
      		UNIQUE KEY ID (ID)
    		);
    		";
    
    	 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    
    	dbDelta($sql);	
    
       }
    }

    And of course I am calling this via...

    register_activation_hook(__FILE__,'myplugin_install');

    Any help is mucho appreciated!

    Cheers.

  2. husar
    Member
    Posted 6 years ago #

    Sorry one update to the code. It should be as follows...

    function myplugin_install() {
       global $wpdb;
       $table_name = $wpdb->prefix . "myplugtable";
       if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
    
          $sql = "CREATE TABLE " . $table_name . " (
    	  Title varchar(250) NOT NULL,
      		Owner varchar(256) NOT NULL,
                    ID varchar(256) NOT NULL,
      		Available datetime NOT NULL,
      		Status varchar(256) NOT NULL,
      		Sound varchar(256) NOT NULL,
      		Versions int(11) NOT NULL,
      		UNIQUE KEY ID (ID)
    		);
    		";
    
    	 require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    
    	dbDelta($sql);	
    
       }
    }
  3. harknell
    Member
    Posted 6 years ago #

    You are hitting the global variable issue in WordPress 2.5. Add a line in the *main part* of your file stating "global $wpdb;"

    Weirdly they made their own global variables non-global in the activation function.

  4. husar
    Member
    Posted 6 years ago #

    I am not using 2.5 but thanks. But I might need to do that when I upgrade this weekend.

    I did solve this but it just came down to the spacing of each line in the create table section. I deleted all the spaces out of the $sql variable. Then return each part it a line. The dbDelta seems to be super picky on how it get the $sql variable.

    Cheers.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags