The next step is to actually create the database table. Rather than executing an SQL query directly, we’ll use the dbDelta function in wp-admin/includes/upgrade.php (we’ll have to load this file, as it is not loaded by default). The dbDelta function examines the current table structure, compares it to the desired table structure, and either adds or modifies the table as necessary, so it can be very handy for updates (see wp-admin/upgrade-schema.php for more examples of how to use dbDelta). Note that the dbDeltafunction is rather picky, however. For instance:

  • You must put each field on its own line in your SQL statement.
  • You must have two spaces between the words PRIMARY KEY and the definition of your primary key.
  • You must use the key word KEY rather than its synonym INDEX and you must include at least one KEY.
  • KEY must be followed by a SINGLE SPACE then the key name then a space then open parenthesis with the field name then a closed parenthesis.
  • You must not use any apostrophes or backticks around field names.
  • Field types must be all lowercase.
  • SQL keywords, like CREATE TABLE and UPDATE, must be uppercase.
  • You must specify the length of all fields that accept a length parameter. int(11), for example.

With those caveats, here are the next lines in our function, which will actually create or update the table. You’ll need to substitute your own table structure in the $sql variable:

 

 

By using this code you can create table in sql and if you want to insert data than use wp insert…

Add in function.php
<?php
global $wpdb;

$appointment_table_name = $wpdb->prefix . “book_an_appointment”;
if($wpdb->get_var(“show tables like ‘$appointment_table_name'”) != $appointment_table_name) {

$sql = “CREATE TABLE ” . $appointment_table_name . ” (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
phone VARCHAR(25) NOT NULL,
date VARCHAR(25) NOT NULL,
time VARCHAR(25) NOT NULL,
comment VARCHAR(1500) NOT NULL,
UNIQUE KEY id (id)
);”;

require_once(ABSPATH . ‘wp-admin/includes/upgrade.php’);
dbDelta($sql);

}
?>