On this page
maybe_create_table( string $table_name, string $create_ddl ): bool
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.
Parameters
$table_namestring Required-
Database table name.
$create_ddlstring Required-
SQL statement to create table.
Return
bool True on success or if the table already exists. False on failure.
Source
File: wp-admin/includes/upgrade.php. View all references
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;
}
Related
Uses
| Uses | Description |
|---|---|
| wpdb::esc_like() wp-includes/class-wpdb.php | First half of escaping for |
| wpdb::get_col() wp-includes/class-wpdb.php | Retrieves one column from the database. |
| wpdb::query() wp-includes/class-wpdb.php | Performs a database query, using current database connection. |
| wpdb::get_var() wp-includes/class-wpdb.php | Retrieves one variable from the database. |
| wpdb::prepare() wp-includes/class-wpdb.php | Prepares a SQL query for safe execution. |
Changelog
| Version | Description |
|---|---|
| 1.0.0 | Introduced. |
© 2003–2022 WordPress Foundation
Licensed under the GNU GPLv2+ License.
https://developer.wordpress.org/reference/functions/maybe_create_table