How to add new column to MYSQL table

2019-01-06 11:10发布

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

assessmentid | q1 | q2 | q3 | q4 | q5 

Say I have a page with a textbox and i type q6 in to the textbox and press a button then the table is updated to

assessmentid | q1 | q2 | q3 | q4 | q5 | q6

Thanks in advance

<?php 
include 'core/init.php';
include 'core/admininit.php';
include 'includes/overall/overall_header.php'; 
adminprotect_page();
include 'includes/adminmenu.php'; 
?>      
<?php

mysql_query("ALTER TABLE `assessment` ADD newq INT(1) NOT NULL AFTER `q10`");

?>
<h1>Input Career Name</h1>

    <form method="post" action="">

      Career Name
      <input type="text" name="newq" size="20">

     <input type="submit"
      name="submit" value="Submit">

</body>
</html>

7条回答
混吃等死
2楼-- · 2019-01-06 11:49

your table:

q1 | q2 | q3 | q4 | q5

you can also do

ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5
查看更多
地球回转人心会变
3楼-- · 2019-01-06 11:50
  • 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

查看更多
叛逆
4楼-- · 2019-01-06 11:54

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...
查看更多
混吃等死
5楼-- · 2019-01-06 11:55
 $table  = 'your table name';
 $column = 'q6'
 $add = mysql_query("ALTER TABLE $table ADD $column VARCHAR( 255 ) NOT NULL");

you can change VARCHAR( 255 ) NOT NULL into what ever datatype you want.

查看更多
甜甜的少女心
6楼-- · 2019-01-06 12:01

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.

查看更多
迷人小祖宗
7楼-- · 2019-01-06 12:09

Something like:

$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
    echo "It worked";
}

Haven't tested it but should work.

查看更多
登录 后发表回答