Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

php - Add new column to wordpress database

I trying update my plugin. So I must upgrade mysql_table. But when trying new column, program get exception.

This is my current 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);

Now I am add colum more one table. I try Alter table, this working one time and add a column but one more refresh I get this error.

This is mycode

$wpdb->query("ALTER TABLE wp_customer_say ADD say_state INT(1) NOT NULL DEFAULT 1");

And this is my error

WordPress database error: [Duplicate column name 'say_state'] ALTER TABLE wp_customer_say ADD say_state INT(1) NOT NULL DEFAULT 1

I see this error and ? try this;

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

and I get this error.

Warning: mysql_num_fields() expects parameter 1 to be resource, integer given in

Help please. Thank you. Sorry bad english.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use this query. I use only mysql-standred for get field name by fast query and this will solve your problem:

$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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...