Create tables with wordpress plugin

If you are making the wordpress plugin, many times we need to create new tables. You will see how easily we can create the wordpress plugin with new table in database.
Using following code:

global $my_db_version;
$my_db_version = "1.0";
function my_install () {
global $wpdb;
global $my_db_version;
$table_name = $wpdb->prefix . "liveshoutbox";
if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
$sql = "CREATE TABLE " . $table_name . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name tinytext NOT NULL,
UNIQUE KEY id (id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
$rows_affected = $wpdb->insert( $table_name, array('name' => $welcome_name) );
add_option("my_db_version", $my_db_version);
}
}

Now that we have the initialization function defined, we want to make sure that WordPress calls this function when the plugin is activated by a WordPress administrator. To do that, we will use the activate_ action hook. If your plugin file is wp-content/plugins/plugindir/pluginfile.php, you’ll add the following line to the main body of your plugin:


register_activation_hook(__FILE__,'my_install');

2 comments

  1. how are you!This was a really quality blog!
    I come from itlay, I was luck to search your topic in yahoo
    Also I learn much in your subject really thank your very much i will come daily

Leave a Reply

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