WordPress codex for creating tables with plugins?

So it says that I have to put a double space between PRIMARY KEY. Does this mean that I have to put a double space between PRIMARY and KEY. Also, what does it mean to put it between the definition of your PRIMARY KEY too? Thanks!

  • 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.
  • 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.

global $wpdb;

$charset_collate = $wpdb->get_charset_collate();

$sql = "CREATE TABLE $table_name (
  id mediumint(9) NOT NULL PRIMARY KEY AUTO_INCREMENT,

  time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,

  name tinytext NOT NULL,

  text text NOT NULL,

  url varchar(55) DEFAULT '' NOT NULL,

  UNIQUE KEY id (id)

) $charset_collate;";

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

Related posts

Leave a Reply

1 comment

  1. This is a good question, and no, no need for an extra space between PRIMARY KEY. The dbDelta() function can be precarious about the SQL statement served as a parameter so don’t use PRIMARY KEY declaration as you would normally. The primary key is declared (PRIMARY KEY) and then the definition (id). You should add the primary key as follows:

    global $wpdb;
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE $table_name (
      id mediumint(9) NOT NULL AUTO_INCREMENT,
      time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
      name tinytext NOT NULL,
      text text NOT NULL,
      url varchar(55) DEFAULT '' NOT NULL,
      PRIMARY KEY  (id)
    ) $charset_collate;";
    
    require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
    dbDelta( $sql );