Zhi V
Zhi V

Reputation: 364

How to create table with dynamic number of columns MYSQL

I'm trying to create table in mysql. There is $column_str which stores the names of the column.

If we have 3 columns it will be $columns_str="123", 4 columns -> $columns_str="1234"

So, I need to create table using variable $columns_str.

This code creates table1 with 1 column: "123":

$columns_str="123"; $table_name = table1;
$connection->query("CREATE TABLE `kcup`.`$table_name` ( `$columns_str` TEXT NOT NULL ) ENGINE = InnoDB;")

I need table with 3 columns: "1","2","3".

Help pls and thank you!

Upvotes: 1

Views: 4790

Answers (2)

Stu
Stu

Reputation: 4150

To create a table with three columns named 1, 2, and 3 when you have a variable $columns_str="123" you could use something like this;

<?php
$columns_str="123";
$table_name = 'table1';
$cols = str_split($columns_str);
$colQuery = '`id` int(11) NOT NULL AUTO_INCREMENT,';
foreach($cols as $col)
{
    $colQuery .= "
        `$col` TEXT NOT NULL,";
}
$colQuery .= "
PRIMARY KEY (`id`)";
$connection->query("CREATE TABLE `kcup`.`$table_name` ( $colQuery ) ENGINE = InnoDB;")

This would run the following SQL command;

CREATE TABLE `kcup`.`table1` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `1` TEXT NOT NULL,
    `2` TEXT NOT NULL,
    `3` TEXT NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = InnoDB;

Upvotes: 2

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

You can't create a table with dynamics columns, but you can simulate it with a table like this one

ID   FIELD    VALUE
1    ID       4345
1    NAME     PAUL
1    SURNAME  SMITH
2    ID       4346
2    NAME     MARC
2    SURNAME  BROWN

The PK of that table is ID, FIELD Addyng a new field is equivalent to add a new row.

So adding the field EMAIL is equivalent to add two rows (one for PAUL and one for MARC) and you will have the following records

ID   FIELD    VALUE
1    ID       4345
1    NAME     PAUL
1    SURNAME  SMITH
2    ID       4346
2    NAME     MARC
2    SURNAME  BROWN
1    EMAIL    [email protected]
2    EMAIL    [email protected]

Upvotes: 1

Related Questions