• Resolved husar

    (@husar)


    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.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter husar

    (@husar)

    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);	
    
       }
    }

    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.

    Thread Starter husar

    (@husar)

    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.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘wpdb to create table is driving me nuts! Please help’ is closed to new replies.