워드프레스 데이터베이스에 새 열 추가
플러그인을 업데이트하려고 합니다.그래서 mysql_table을 업그레이드해야 합니다.그러나 새 열을 시도할 때 프로그램에서 예외가 발생합니다.
현재 테이블은 다음과 같습니다.
$sql = "CREATE TABLE {$table_name} (
say_id int(11) not null AUTO_INCREMENT,
customer_mail text not null,
customer_name text not null,
customer_messagge text not null,
messagge_date_time datetime not null,
PRIMARY KEY (say_id)
)ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1";
require_once(ABSPATH . "wp-admin/includes/upgrade.php");
dbDelta($sql);
이제 컬럼을 한 테이블 더 추가하겠습니다.Alter table을 한 번 시도해보고 열을 추가했는데 한 번 더 새로 고치면 이 오류가 나타납니다.
이것은 mycode입니다.
$wpdb->query("ALTER TABLE wp_customer_say ADD say_state INT(1) NOT NULL DEFAULT 1");
그리고 이건 내 실수야
WordPress 데이터베이스 오류: [중복 열 이름 'say_state'] ALTER TABLE wp_customer_SAY ADD SAY_state INT(1) NULL DEFAULT 1이 아닙니다.
이 에러가 표시되고, 이것을 시험해 보겠습니다.
$query = $wpdb->query("select * from wp_customer_say");
$respond = mysql_num_fields( $query );
$column_array = array();
for($i = 0; $i < $respond ; $i++):
$column_array[] = mysql_field_name($query,$i);
endfor;
if( !in_array("say_state",$column_array) ):
$wpdb->query("ALTER TABLE wp_customer_say ADD say_state INT(1) NOT NULL DEFAULT 1");
endif;
이 에러가 표시됩니다.
Warning: mysql_num_fields() expects parameter 1 to be resource, integer given in
도와주세요.감사해요.영어가 서툴러서 미안해.
이 쿼리를 사용합니다.fast query에 의한 get field name에는 mysql-standred만 사용합니다.이것에 의해서, 다음의 문제가 해결됩니다.
$row = $wpdb->get_results( "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'wp_customer_say' AND column_name = 'say_state'" );
if(empty($row)){
$wpdb->query("ALTER TABLE wp_customer_say ADD say_state INT(1) NOT NULL DEFAULT 1");
}
아래 방법을 사용하여 WordPress에 열 이름이 있는지 확인할 수 있습니다.
$myCustomer = $wpdb->get_row("SELECT * FROM wp_customer_say");
//Add column if not present.
if(!isset($myCustomer->say_state)){
$wpdb->query("ALTER TABLE wp_customer_say ADD say_state INT(1) NOT NULL DEFAULT 1");
}
열이 없는 경우 테이블에 새 열을 추가하는 가장 올바른 방법입니다.
/*@ Add status column if not exist */
global $wpdb;
$dbname = $wpdb->dbname;
$marks_table_name = $wpdb->prefix . "wpsp_mark";
$is_status_col = $wpdb->get_results( "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `table_name` = '{$marks_table_name}' AND `TABLE_SCHEMA` = '{$dbname}' AND `COLUMN_NAME` = 'status'" );
if( empty($is_status_col) ):
$add_status_column = "ALTER TABLE `{$marks_table_name}` ADD `status` VARCHAR(50) NULL DEFAULT NULL AFTER `attendance`; ";
$wpdb->query( $add_status_column );
endif;
@Amandeep Wadhawan의 대답보다 조금 더 좋은 방법이 있다는 것을 덧붙이고 싶다.
register_activation_hook(__FILE__, 'install_tables');
function install_tables()
{
update_options('my_plugins_current_db_version', 0); // Replace 0 with whatever your final database version is
// Code here to create the final version of your database tables
}
add_action('plugins_loaded', 'update_databases');
public function update_databases()
{
global $wpdb;
$prefix = $wpdb->prefix;
$a_table_to_update = $prefix . $a_table_to_update;
$current_version = get_option('my_plugins_current_db_version', 0);
switch($current_version)
{
// First update
case 0:
// first update code goes here (alter, new table, whatever)
$current_version++;
case 1:
// next update code goes here
$current_version++;
}
update_option('my_plugins_current_db_version', $current_version);
}
넌 그저 네가 원하는 걸 확실히 하기만 하면 돼install_tables()
이 함수는 항상 최종 버전 번호를 반영하는 테이블을 만들고,my_plugins_current_db_version
옵션을 최종 버전 번호로 지정합니다.
그리고 나서update_databases()
함수가 증가하는지 확인만 하면 됩니다.$current_version
모든 후속 케이스에 앞서서
이 셋업에서는 불필요한 쿼리를 하지 않고 무작정 갱신할 수 있습니다.컬럼이나 테이블이 먼저 존재하는지 아닌지를 알 수 있습니다.또한 적은 쿼리가 항상 도움이 됩니다.특히 업데이트 코드가 다음 웹 사이트에서 기동하고 있는 경우에는 더욱 그렇습니다.plugins_loaded
갈고리를 채우다
또한 훨씬 깔끔하고 명확한 업그레이드 경로를 보여주며 필요한 업데이트만 수행하므로 효율이 향상됩니다.
Rikesh의 옵션(업투표까지!)은 매우 마음에 듭니다만, 다음과 같이 변경될 수 있는 정보의 하드코딩을 방지하기 위해 노력하고 있습니다.$table_prefix
에서wp-config.php
파일, 이 옵션이 더 안전합니다.
// Replace `table_name` with the actual table name
$table = $table_prefix.'table_name';
// And use sprintf to pass the table name
// Alternatively, you can use $table instead of sprintf,
// if you use double quotes such as shown here
$myCustomer = $wpdb->get_row( sprintf("SELECT * FROM %s LIMIT 1", $table) );
// If you prefer not using sprintf, make sure you use double quotes
// $myCustomer = $wpdb->get_row( "SELECT * FROM $table LIMIT 1" );
// Replace "missing_field" by the column you wish to add
if(!isset($myCustomer->missing_field)) {
$wpdb->query( sprintf( "ALTER TABLE %s ADD phone2 VARCHAR(255) NOT NULL", $table) );
// Alternate example using variable
// $wpdb->query( "ALTER TABLE $table ADD phone2 VARCHAR(255) NOT NULL") );
}
훌륭한 솔루션을 작성했습니다.모든 경우에 효과가 있습니다.
$check_column = (array) $wpdb->get_results( "SELECT count(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME = '{$wpdb->prefix}my_table' AND COLUMN_NAME = 'some_name'" )[0];
$table_name = $wpdb->prefix . 'my_table';
$check_column = (int) array_shift($check_column);
if($check_column == 0) {
$wpdb->query(
"ALTER TABLE $table_name
ADD COLUMN `some_name` VARCHAR(55) NOT NULL
");
}
$myCustomer = $wpdb->get_row("SELECT * FROM wp_customer_say");
//Add column if not present.
if(!isset($myCustomer->say_state)){
$wpdb->query("ALTER TABLE wp_customer_say ADD say_state INT(1) NOT NULL DEFAULT '' ");
데이터베이스에 레코드가 없는 경우 이 코드는 실패합니다.데이터베이스에 저장된 레코드가 하나 이상 있는 경우에만 작동합니다.
언급URL : https://stackoverflow.com/questions/21330932/add-new-column-to-wordpress-database
'sourcecode' 카테고리의 다른 글
JSON에 목록 직렬화 중 (0) | 2023.02.22 |
---|---|
워드프레스 투고 수정 시간 변경 방법 (0) | 2023.02.22 |
많은 데이터를 포함하는 AngularJS 무한 스크롤 (0) | 2023.02.22 |
서브슬라이밍 텍스트용 JSX 포메터가 있나요? (0) | 2023.02.22 |
mongodb에 날짜/시간을 저장하는 가장 좋은 방법 (0) | 2023.02.22 |