How to add new column to MYSQL table?

后端 未结 8 1684
南旧
南旧 2020-11-27 12:38

I am trying to add a new column to my MYSQL table using PHP. I am unsure how to alter my table so that the new column is created. In my assessment table I have:



        
相关标签:
8条回答
  • 2020-11-27 13:18
    • You can add a new column at the end of your table

      ALTER TABLE assessment ADD q6 VARCHAR( 255 )

    • Add column to the begining of table

      ALTER TABLE assessment ADD q6 VARCHAR( 255 ) FIRST

    • Add column next to a specified column

      ALTER TABLE assessment ADD q6 VARCHAR( 255 ) after q5

    and more options here

    0 讨论(0)
  • 2020-11-27 13:21

    You should look into normalizing your database to avoid creating columns at runtime.

    Make 3 tables:

    1. assessment
    2. question
    3. assessment_question (columns assessmentId, questionId)

    Put questions and assessments in their respective tables and link them together through assessment_question using foreign keys.

    0 讨论(0)
  • 2020-11-27 13:21

    for WORDPRESS:

    global $wpdb;
    
    
    $your_table  = $wpdb->prefix. 'My_Table_Name';
    $your_column =                'My_Column_Name'; 
    
    if (!in_array($your_column, $wpdb->get_col( "DESC " . $your_table, 0 ) )){  $result= $wpdb->query(
        "ALTER     TABLE $your_table     ADD $your_column     VARCHAR(100)     CHARACTER SET utf8     NOT NULL     "  //you can add positioning phraze: "AFTER My_another_column"
    );}
    
    0 讨论(0)
  • 2020-11-27 13:34

    Based on your comment it looks like your'e only adding the new column if: mysql_query("SELECT * FROM assessment"); returns false. That's probably not what you wanted. Try removing the '!' on front of $sql in the first 'if' statement. So your code will look like:

    $sql=mysql_query("SELECT * FROM assessment");
    if ($sql) {
     mysql_query("ALTER TABLE assessment ADD q6 INT(1) NOT NULL AFTER q5");
     echo 'Q6 created'; 
    }else...
    
    0 讨论(0)
  • 2020-11-27 13:40

    your table:

    q1 | q2 | q3 | q4 | q5
    

    you can also do

    ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5
    
    0 讨论(0)
  • 2020-11-27 13:40
    ALTER TABLE `stor` ADD `buy_price` INT(20) NOT NULL ;
    
    0 讨论(0)
提交回复
热议问题