00 Votes

MySQL: How to add Column to Table dynamically

Question by Sledge | 2016-06-12 at 20:52

I have a MySQL database and up to now, I have always used phpMyAdmin for adding, editing and creating new columns whenever I needed a new one.

However, now, I would like to create a new column with an individual name just directly out of a PHP script. Is this feasible? Every time going via phpMyAdmin is too inconvenient for me.

ReplyPositiveNegative
0Best Answer0 Votes

Of course, you can do that. phpMyAdmin is not doing anything else in the background when adding some new columns than executing the necessary MySQL commands. And keep in mind, that phpMyAdmin is also written in PHP. So, there are enough reasons for that you can do that, too. The command, you are searching for is:

ALTER TABLE tab ADD col definition;

With ALTER TABLE, you can modify your table. In the line above, you have to replace "tab" with the name of your table, "col" with the name your new column should have and "definition" with the kind of column, you want to create. Here are two examples creating the columns "col1" and "col2" in the table "tab":

ALTER TABLE tab ADD col1 VARCHAR(50);
ALTER TABLE tab ADD col2 INT;

In the first example, we are creating a column with the name "col1" and with the data type VARCHAR(50), and the second example, "col2" with integer as data type.
2016-06-13 at 20:20

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.