Bala
Bala

Reputation: 3638

How to add comma separated values to database as separate records?

I have a table named product_table as below with two fields product_id and comp_prod

The values for comp_prod will be sent as comma separated values like 4,3

but the value of product_id will be common

I want to insert the comma separated values as separate rows as follows with product_id as common. How can i do that using php and mysql ?

product_table

+-----+----------+-----------------+    
| id | product_id  |comp_prod      |   
+-----+----------+-----------------+    
|1  |      339     |  4            |   
|2  |      339     |  5            |   
+------------+---------------------+     

Upvotes: 1

Views: 8298

Answers (5)

Naveen Kumar
Naveen Kumar

Reputation: 4601

$pro=5;

$comp_proSplit= explode(",", $comp_pro);

$cnt=count($comp_proSplit);

for($i=0;$i<$cnt;$i++)
{
mysql_query("insert into product_table(product_id,comp_prod) 
values ($pro, $comp_proSplit[$i])");
}

Hope it helps

Upvotes: 5

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175


$sql = array;
$yourArrFromCsv = explode(",", $yourCSV);
//then insert to db
foreach( $yourArrFromCsv as $row ) {
    $sql[] = '('.$compProdId.', '.$row.')';
}
mysql_query('INSERT INTO table (comp_prod, product_id) VALUES '.implode(',', $sql));

Do you mean something like that

Upvotes: 1

denislexic
denislexic

Reputation: 11342

As the others mentioned, then loop it. Here is an example. There might be a mistake, but the idea is there.

foreach($arrayOfEachRowInCSV as $array){
   $product_id = $array['product_id'];
   $array_comp_prod = explode(",", $array['comp_prod_comma_seperated']);
   foreach($array_comp_prod as $comp_prod){
        $sql = "INSERT INTO table_name (product_id, comp_prod) VALUES('{$product_id}','{$comp_prod}')";
   }
}

I hope this helps

Upvotes: 1

Kannan Prasad
Kannan Prasad

Reputation: 1806

Use explode function

Upvotes: 1

xdazz
xdazz

Reputation: 160833

Use explode function to split the string into array.

Upvotes: 1

Related Questions