How to Create a Table in WordPress Database |
X

Congrats, You are Subscribed to Receive Updates.

How to Create a Table in WordPress Database


How to Create a Table in WordPress Database is one of a basic thing required for all the wordpress plugin works. The following steps help you to create your own table with the help of Wpdb object. Before getting in to the coding. you need to remember two things, 1.you have to declare the global variable $wpdb on your table creation function.

global $wpdb;

2. you have to require the upgrades file to  play with wordpress databases, Else your code wont work with out showing any error. so just use the following code.

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

Now, we are ready to code and create own own custom table inside your wordpress CMS.  We need to use the WordPress table prefix for our custom table creation. so just use the following snippet while naming you table.

$find_a_plate = $wpdb->prefix.'my_table_name';

N ow, we are ready to write our sql code to create table.

$sql_query = "CREATE TABLE IF NOT EXISTS $find_a_plate  (
		  `id` int(11) NOT NULL AUTO_INCREMENT,
		  `person_name` varchar(64) NOT NULL default '',
		  `contact_no` varchar(128) NOT NULL default '',
		  `email` varchar(15) NOT NULL default '',		  
		  UNIQUE KEY id (id)
		)ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;";

Than, now your query is ready to create a table. Just use the following function and pass the query as parameter and create table.

dbDelta($sql_query);

That’s it for new table creation. if you want to get complete code, just copy use the following code.

require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

if(!function_exists('kv_create_tables')) {
        add_action('admin_init', 'kv_create_tables');
	function kv_create_tables () {
		global $wpdb;
		$find_a_plate = $wpdb->prefix.'my_table_name';
		$sql_query= "CREATE TABLE IF NOT EXISTS $find_a_plate  (
		  `id` int(11) NOT NULL AUTO_INCREMENT,
		  `person_name` varchar(64) NOT NULL default '',
		  `contact_no` varchar(128) NOT NULL default '',
		  `email` varchar(15) NOT NULL default '',		  
		  UNIQUE KEY id (id)
		)ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;";

		dbDelta($sql_query);
	}
}

Any queries comment below.

commenter

About Varadharaj V

The founder of Kvcodes, Varadharaj V is an ERP Analyst and a Web developer specializing in WordPress(WP), WP Theme development, WP Plugin development, Frontaccounting(FA), Sales, Purchases, Inventory, Ledgers, Payroll & HRM, CRM, FA Core Customization, PHP and Data Analyst. Database Management Advance Level

Comment Below

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

*

Current ye@r *

Menu

Sidebar