How to create tables on plugin installation in wordpress

While developing a plugin for WordPress, you will almost certainly find that you need to store some information in the WordPress database.Sometimes we need to add some data to the tables too.
Wordprss has register_activation_hook function which registers a plugin function to be run when the plugin is activated.Lets take example of code here.You need to put the below to wp-content/plugins/your-plugin/plugin.php.

$your_db_name = $wpdb->prefix . 'your_db_name';
// function to create the DB / Options / Defaults					
function your_plugin_func_install() {
   	global $wpdb;
  	global $table_name = $wpdb->prefix."contacts";
	// create the ECPT metabox database table
	if($wpdb->get_var("show tables like '$table_name'") != $table_name) 
		$sql = "CREATE TABLE " . $table_name . " (
		`id` mediumint(9) NOT NULL AUTO_INCREMENT,
		`name` mediumtext NOT NULL,
		`email` tinytext NOT NULL,
		`address` tinytext NOT NULL,
		`phone` tinytext NOT NULL,
		UNIQUE KEY id (id)
		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// Here registering our function on plugin activation

Leave a Reply