Adding New Columns to MYSQL Tables
When working with MYSQL databases, it may become necessary to add new columns to existing tables. This article demonstrates how to use PHP to alter a table and add a new column.
Example
Consider a table named "assessment" with the following columns:
assessmentid | q1 | q2 | q3 | q4 | q5
To add a new column named "q6," perform the following steps:
Use the ALTER TABLE statement with the ADD clause to define the new column. In this example:
mysql_query("ALTER TABLE `assessment` ADD q6 INT(1) NOT NULL AFTER `q10`");
Create a form to collect user input for the new column:
<form method="post" action=""> <input type="text" name="newq" size="20"> <input type="submit" name="submit" value="Submit"> </form>
Process the form submission to update the table with the new value:
// Process the form submission // ... // Add the new column value to the table mysql_query("UPDATE `assessment` SET q6 = '" . $_POST['newq'] . "' WHERE ..."
Note:
Alternatively, you can add a new column after an existing column using the following syntax:
ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5
The above is the detailed content of How can I add a new column to a MySQL table using PHP?. For more information, please follow other related articles on the PHP Chinese website!