maybe_add_column()
云策文档标注
概述
maybe_add_column() 函数用于向数据库表添加列,如果该列不存在则执行添加操作。它检查列是否存在,避免重复添加,并返回操作结果。
关键要点
- 函数检查指定列是否已存在于数据库表中,若存在则直接返回 true。
- 如果列不存在,则执行提供的 SQL 语句($create_ddl)来添加列。
- 添加后再次检查列是否存在以确认操作成功,返回 true 表示成功或列已存在,false 表示失败。
- 参数包括 $table_name(表名)、$column_name(列名)和 $create_ddl(添加列的 SQL 语句)。
- 内部使用 $wpdb->get_col() 和 $wpdb->query() 进行数据库操作。
代码示例
function maybe_add_column( $table_name, $column_name, $create_ddl ) {
global $wpdb;
foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
if ( $column === $column_name ) {
return true;
}
}
// Didn't find it, so try to create it.
$wpdb->query( $create_ddl );
// We cannot directly tell that whether this succeeded!
foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
if ( $column === $column_name ) {
return true;
}
}
return false;
}
原文内容
Adds column to a database table, if it doesn’t already exist.
Parameters
$table_namestringrequired-
Database table name.
$column_namestringrequired-
Table column name.
$create_ddlstringrequired-
SQL statement to add column.
Source
function maybe_add_column( $table_name, $column_name, $create_ddl ) {
global $wpdb;
foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
if ( $column === $column_name ) {
return true;
}
}
// Didn't find it, so try to create it.
$wpdb->query( $create_ddl );
// We cannot directly tell that whether this succeeded!
foreach ( $wpdb->get_col( "DESC $table_name", 0 ) as $column ) {
if ( $column === $column_name ) {
return true;
}
}
return false;
}
Changelog
| Version | Description |
|---|---|
| 1.3.0 | Introduced. |