简体   繁体   中英

Naming columns with alter table in MySQL using variables

Is it possible to name a column in a table using variables? For example lets say I want to create a table with columns named col1, col2, col3 using a while loop where the integer in the column name equals the current position in the loop. What should I replace the dots with below?

ALTER TABLE table1 ADD ... INT(11) DEFAULT NULL;
$numberOfColumnsRequired = $_POST['user_requested_tables'];
$i = 1;
while ($i < $numberOfColumnsRequired && $i <= 30) {
    $result = mysqli_query($link,"ALTER TABLE table1 ADD `col{$i}` INT(11) DEFAULT NULL");
    $i++;
}

Something like this will accomplish the task... However this opens the door to a lot of potentially nasty things to happen.

Why do you need this? What are you trying to do? Id rather propose a better solution.

Edit: added a maximum number of columns that can be added.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM