函数文档

maybe_create_table()

💡 云策文档标注

概述

maybe_create_table() 函数用于在数据库中创建表,如果表不存在则执行创建操作。它通过查询现有表来避免重复创建,不依赖 MySQL 的 IF NOT EXISTS 语句。

关键要点

  • 检查表是否存在:使用 SHOW TABLES LIKE 查询,如果表已存在则返回 true。
  • 创建表:如果表不存在,执行传入的 SQL 创建语句。
  • 返回值:成功或表已存在时返回 true,失败时返回 false。
  • 参数:$table_name(表名,字符串,必需)和 $create_ddl(创建表的 SQL 语句,字符串,必需)。
  • 依赖 WordPress 数据库类 $wpdb,使用相关方法如 prepare()、get_var() 和 query()。

代码示例

require_once ABSPATH . 'wp-admin/includes/upgrade.php';
global $wpdb;
$tablename = 'wpdocs_myTable';
$main_sql_create = 'CREATE TABLE ' . $tablename . ';';
maybe_create_table( $wpdb->prefix . $tablename, $main_sql_create );

注意事项

  • 调用此函数前需手动包含 upgrade.php 文件,否则可能导致白屏错误。
  • 函数无法直接判断创建操作是否成功,需通过再次查询表名来验证。

📄 原文内容

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

Description

This method checks for an existing database table 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_namestringrequired
Database table name.
$create_ddlstringrequired
SQL statement to create table.

Return

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

Source

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;
}

Changelog

Version Description
1.0.0 Introduced.

User Contributed Notes