How to Add a Column to a MySQL Table Using PHP



PHP







In this article, we show how to add a new column to a MySQL table using PHP.

We add a new column to a MySQL table using PHP to write the MySQL query to add the column the table.





So the above is the PHP code to add a column to a MySQL table at the end of table, meaning it will be the last column.

So a column named email is added to the last column of the table. So if the table had 2 columns named first name and last name. It will now contain first name, last name, and email, in that order.

We'll now show how to tie this in completely with the full PHP code to add a column to a MySQL table.



So, first, we must connect to the database.

After we do this, we create a variable named $add. This $add variable is set equal to a mysql_query() function that has the parameter "ALTER TABLE customers ADD email VARCHAR(50) NOT NULL". This adds the column, email, to the customers table. PHP.

The email column is of type VARCHAR(50) NOT NULL. This makes it a variable string up to 50 characters in length.


How to Add a Column After a Specified Column

So the code above shows how to add a column to the end of a table. The column you add will be the last column of the table.

However, you may not want to add the column to the end of a table. You may want to add it after a specific column.

The MySQL query below is the general format to add a column after a specified column.



So the code above adds a column named email of type VARCHAR(50) after the column firstname to the table customers.

We'll now show how to tie this in completely with the full PHP code to add a column to a MySQL table after a specified column.



So the code above adds a column named email of type VARCHAR(50) after the column named firstname.

So the MySQL keyword AFTER can enable us to add columns after a specified column in a table.


How to Add a Column to the Beginning of a Table

Now we show how to add a column to the beginning of a MySQL table.

The MySQL query below is the general format to add a column to the beginning of a table is shown below.



So the code above adds a column named email of type VARCHAR(50) after the column firstname to the table customers.

We'll now show how to tie this in completely with the full PHP code to add a column to a MySQL table after a specified column.



So this code shows how to add a column to the beginning of a MySQL table using PHP.


Related Resources

How to Add a Primary Key to a Column of a MySQL Table Using PHP

How to Make a Column of a MySQL Table Unique Using PHP

How to Rename a Column of a MySQL Table Using PHP

How to Delete a Column of a MySQL Table Using PHP

How to Concatenate Column Values in MySQL Using PHP

HTML Comment Box is loading comments...