maybe_create_table() WordPress Function

This function will maybe create a new database table if it doesn't already exist. This is useful for plugins that need to create new tables when they're installed.

maybe_create_table( string $table_name, string $create_ddl ) #

Creates a table in the database, if it doesn’t already exist.


Description

This method checks for an existing database and creates a new one if it’s not already present. It doesn’t rely on MySQL’s "IF NOT EXISTS" statement, but chooses to query all tables first and then run the SQL statement creating the table.


Top ↑

Parameters

$table_name

(string)(Required)Database table name.

$create_ddl

(string)(Required)SQL statement to create table.


Top ↑

Return

(bool) True on success or if the table already exists. False on failure.


Top ↑

Source

File: wp-admin/includes/upgrade.php

function maybe_create_table( $table_name, $create_ddl ) {
	global $wpdb;

	$query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table_name ) );

	if ( $wpdb->get_var( $query ) === $table_name ) {
		return true;
	}

	// Didn't find it, so try to create it.
	$wpdb->query( $create_ddl );

	// We cannot directly tell that whether this succeeded!
	if ( $wpdb->get_var( $query ) === $table_name ) {
		return true;
	}

	return false;
}


Top ↑

Changelog

Changelog
VersionDescription
1.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.