简体   繁体   English

如何使用动态列数MYSQL创建表

[英]How to create table with dynamic number of columns MYSQL

I'm trying to create table in mysql. 我正在尝试在mysql中创建表。 There is $column_str which stores the names of the column. $column_str存储列的名称

If we have 3 columns it will be $columns_str="123" , 4 columns -> $columns_str="1234" 如果我们有3列, $columns_str="123" ,4列 - > $columns_str="1234"

So, I need to create table using variable $columns_str. 所以,我需要使用变量$ columns_str创建表。

This code creates table1 with 1 column: "123": 此代码创建table1,其中包含1列:“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". 我需要有3列的表:“1”,“2”,“3”。

Help pls and thank you! 请帮助,谢谢!

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; 要创建具有三列命名表123 ,当你有一个变量$columns_str="123" ,你可以使用这样的事情;

<?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; 这将运行以下SQL命令;

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;

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. 该表的PK是ID,FIELD Addyng一个新字段相当于添加一个新行。

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 因此添加字段EMAIL相当于添加两行(一行用于PAUL,一行用于MARC),您将拥有以下记录

ID   FIELD    VALUE
1    ID       4345
1    NAME     PAUL
1    SURNAME  SMITH
2    ID       4346
2    NAME     MARC
2    SURNAME  BROWN
1    EMAIL    paul.smith@email.com
2    EMAIL    marc.brown@email.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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