2

So, I have problem with adding columns to table tablica, tablica has only id column and trough loop I am adding column names with ALTER query and then I am adding values from table prva with query INSERT, here's my code:

    if(isset($_POST['submit']))
    {
        mysql_query("CREATE TABLE tablica (id INT PRIMARY KEY AUTO_INCREMENT)");

        if(isset($_POST['kolona']))
            {
                foreach($_POST['kolona'] as $vrednost)
                  {  

                mysql_query("ALTER TABLE tablica ADD $vrednost text");

                mysql_query("INSERT INTO tablica ($vrednost) SELECT $vrednost FROM prva");}

            }
    }

I have problem in what way columns are added, first column is ok, then the second one begins where the first ends, so my ouput is something like this:

id   column1  column2
1     a1       NULL
2     a2       NULL
5     NULL     b1
6     NULL     b2

and it needs to be:

id  column1   column2
1    a1        b1
2    a2        b2

so I need to put the column2 in the place, than and id's will be sorted also i think. Can anyone help? Tnx

4

1 回答 1

0

You are doing inserts where you only supply one column:

INSERT INTO tablica ($vrednost) SELECT $vrednost FROM prva

This will force the other columns that don't have defaults or autoincrement to be null.

Instead of doing the insert in every iteration of the loop, you should get the different $vrednost in the foreach iterations and after the loop do a query something like:

INSERT INTO tablica (vrednost1,vrednost2,...) SELECT vrednost1,vrednost2,... FROM prva
于 2013-10-04T23:41:54.477 回答