0

I have a problem with comma separated values when fetch and insert to 1 table from to another table,

my problem is,

I am using PHP, Mysql

table_1 has comma separated values like this

1 | apple1, apple2, apple3 
2 | samsung1,samsung2, samsung3, samsung4
3 | nokia1,nokia2

I want to fetch these values from above table and inset to another table with same id, like this
table_2
1 | 1 | apple1
2 | 1 | apple2
3 | 1 | apple3
4 | 2 | samsung1
5 | 2 | samsung2
6 | 2 | samsung3
7 | 2 | samsung4
8 | 3 | nokia1
9 | 3 | nokia2

please anyone can help me to resolve this problem I have a big comma separated table to insert with this,

thanks!

Thush
  • 1
  • 4
  • Hi, I used explode function to insert values, itz worked well only for values, id failed to insert duplicate ID to those – Thush Sep 27 '13 at 10:15

2 Answers2

0

insert, then transform.

load infile 

is what you need for insert

to convert columns to rows, select id, col1 from table union all id col2 from table union all id, col3 from table...

AdrianBR
  • 2,762
  • 1
  • 15
  • 29
0

Lets for example you have this value at once.. apple1,apple2,apple3 and i think a variable will contain them for example it is $container it is a string so make it first an array as

$arr=(explode(",", $container));

now here is a approach of foreach loop in php and if you are geting id for each $container uniquely then just do it as

$id //your id container variable

apply your insertion query as:

foreach($arr as $val)
{
mysqli_query($con, "insert into table_name set r_id='$id',val='$val'");
}

it will insert your comma seperated string for each unique row...

Dinesh
  • 4,066
  • 5
  • 21
  • 35
  • Yes dr, but how can I insert same ID with same result, as I mentioned above in my second table. using this method I can only insert apple1, apple2, apple3 values, but I failed to insert ID Thanks for your time – Thush Sep 27 '13 at 10:32
  • are you getting id from somewhere ....? hmmm – Dinesh Sep 27 '13 at 10:34
  • id get from first table, eg : id=1 for apple, id=2 for samsung like, – Thush Sep 27 '13 at 10:55