0

just wondering how to insert dynamic column to existing MySQL table? For example: I already have "sampletable" and I want to make input fields that can add dynamic column to the existing table, example: column1, column2, column3. How to do that with dynamic numbering?

Barmar
  • 741,623
  • 53
  • 500
  • 612
pasaisea
  • 111
  • 2
  • 13
  • 3
    If you need to do this, you're probably designing your database wrong. The only way to add a column to a table is with `ALTER TABLE`, there's no such thing as dynamic columns. – Barmar Oct 17 '14 at 03:35
  • 1
    If you need to calculate column names dynamically, you have to use dynamic SQL with `PREPARE`. – Barmar Oct 17 '14 at 03:36
  • Hi, thanks for the quick reply. Okay so by the means there is no such thing as dynamic columns, so I should already make column1, column2, column3, in the table then make input fields which connects to the existings columns in the database right? What if the user who make input fields only want to input column1 only? column2 and column3 will be sitting empty in the table, hence thats why I want to create a column with can be added to table suited to the user's needs. – pasaisea Oct 17 '14 at 03:41
  • 3
    This doesn't pass the smell test.. You shouldn't be doing this.. What's the purpose behind it? – John Ruddell Oct 17 '14 at 03:41
  • 2
    Like I said, you're doing this wrong if you think you need dynamic columns. Anything that varies dynamically should be in values, not columns. – Barmar Oct 17 '14 at 03:43
  • If you're trying to have dynamic attributes for database entries, do it in a separate table, whose columns are `item_id`, `attribute_name`, `attribute_value`. Then you'll have a row for each attribute. – Barmar Oct 17 '14 at 03:45
  • I wouldn't ever let users alter tables or input stuff like that.. And just like barmar said this is a bad idea... Asking for issues in the future... How many columns are you going to allow to be added?? How many users? – John Ruddell Oct 17 '14 at 03:46
  • everybody is right, it was a risky thing to do, thats why I ask for opinions first in here if its possible or not. Basically I want to make a web application (car's service quotation), and when the service department issue a new car's service quotation, the user can add service1, price1, service2, price3, service3, price3, service4, price4, customized for their needs. If there only 2 services used, then the column in table only service2, price2, service2, price2. I'm sorry to confuse you all, i'm still young and noob so many new things to learn – pasaisea Oct 17 '14 at 03:56
  • what i'm trying to achieve is web form that connects to database and generate something kinda like this http://cdn.vertex42.com/ExcelTemplates/Images/invoices/auto-repair-invoice-template.png – pasaisea Oct 17 '14 at 04:01
  • that is fine, but you don't need to add columns to the database to do that :) you should have in the database the data related to each car and stuff of that nature... this way if someone needs a quote you plug in the car part that needs to be replaced and the type of car (make model etc) and then run a query to pull out the price associated with that + labor... in other words you need a fairly expansive database with vehicle information – John Ruddell Oct 17 '14 at 04:06

3 Answers3

2

I would agree with @Barmar that your SQL table structure is wrong if you are trying to do this. What you are trying to do in this case is what's called a "one to many" relationship. This is usually achieved by doing something like the following.

Table 1: Contains columns for all the usual data (non-"dynamic" columns in your terms), and a unique ID column which all good database tables should have

Table 2: An ID column, and column that refers to the ID column on table one and a column for the data that goes in the dynamic column.

Now you can store your values that you would normally store in "dynamic columns" in individual rows on the second table.

Example

//  sample:
//
// | id | name |
//
// dynamic_values:
//
// | id | sample_id | value |

// Selecting data

SELECT * FROM sample WHERE id = 1;
SELECT * FROM dynamic_values WHERE sample_id = 1;

// Querying on "dynamic columns"
SELECT * FROM sample s LEFT JOIN dynamic_values d ON d.sample_id = s.id WHERE d.value = 'something';
Scopey
  • 6,269
  • 1
  • 22
  • 34
1

Try This set of code for Dynamic Column Creation for Existing Table.

SET SQL_SAFE_UPDATES = 0;
        Drop TEMPORARY table if exists Temp_Report;
        CREATE TEMPORARY TABLE Temp_Report (Report_Date Date);

        Drop TEMPORARY table if exists Temp_Product_Tax;
        CREATE TEMPORARY TABLE Temp_Product_Tax as SELECT concat(REPLACE(Tax_category,' ','_'),'|',Taxvalue) as 'Tax_category',Taxvalue FROM tax_category c left join taxmaster t on c.id=t.catid ; -- where c.is_Product =1

    select * from Temp_Product_Tax;
            set Count_1=(SELECT COUNT(*) FROM Temp_Product_Tax);
                set Var_1=0;     
                    While(Count_1>Var_1) do
                            set @Col_Name=Concat( Var_1+1,'_',REPLACE((select Tax_category from Temp_Product_Tax limit Var_1,1),'.','_'),' Double(15,2)');

                            set @Col_Name=Concat('ALTER TABLE Temp_Report ADD COLUMN ', @Col_Name) ;
                            PREPARE stmt FROM @Col_Name;
                            EXECUTE stmt;

                    set Var_1=Var_1+1;
                    END While;  

    select * from Temp_Report;

    SET SQL_SAFE_UPDATES = 1;
0

In fact, what you intend to do, ie, adding dynamic columns is not at all a good practice I think. Anyway You can do that using ALTER TABLE

for($i=1;$i<4;$i++){

    mysqli_query("ALTER TABLE mytable ADD COLUMN `input.$i` VARCHAR(40)",$db_con);
}

But I would suggest the same way, which is BARMER mentioned in the above comments.

Mad Angle
  • 2,347
  • 1
  • 15
  • 33
  • 1
    You need backticks around the column name if it contains a dot. – Barmar Oct 17 '14 at 03:42
  • I would just leave out the dot in the first place. Not that it really matters, since this whole approach is wrong-headed. – Barmar Oct 17 '14 at 03:46
  • Yeah I know that. Adding columns dynamically to the table is a complete fault. I don't know why the OP is doing that. – Mad Angle Oct 17 '14 at 03:49