-3

How can I insert an array into a database in one row

    prod_id | user_id | quantity 
    1111    | 5       | 123
    1234    | 5       | 11
    234     | 5       | 1

if I have this table and want to select prod_id for each user and insert it into another table as

    prodid          qun        userid
    1111,1234,234   123,11,1     5

How I can get this result?

I try to use json but it returned an array and didn't store in the database.

<?php
    $sql = "select * from cart where userid=5";
    $result = mysql_query($sql);
    while($row = mysql_fetch_array($result)){
    $prodid = $row['proid'];
    $qun = array($row['qun']);
    $prod[] = array('prodid' => $prodid);
    $quantity[]=array('$qun' => $data);
    }
    $quntatity= json_decode(json_encode($qun ));
    $products= json_decode(json_encode($prod));
    $sql = "insert into products( userid,products ,quantity) values('5',$products','$quntatity')";
    mysql_query($sql) or die(mysql_error()) ;


?>
Rabab
  • 1
  • 6
  • possible duplicate of [Inserting multiple rows in a single SQL query?](http://stackoverflow.com/questions/452859/inserting-multiple-rows-in-a-single-sql-query) – Marvin Fischer Jul 13 '15 at 11:45
  • use atleast MySQLi or PDO for safety – Kavvson Empcraft Jul 13 '15 at 11:47
  • @SidiaStudios no i have user add more one product i want insert all product id in one row in database and when i want to retrieve it i can – Rabab Jul 13 '15 at 11:52
  • Why do people insist on trying to use databases as though they were simply text files.... use a properly normalised database and it will be your friend.... try to store comma-separated values in a column instead, and it will hate you and do everything in its power to make your life difficult and miserable – Mark Baker Jul 13 '15 at 11:52

1 Answers1

0

Using GROUP_CONCAT to resolve like this

   $sql ="SELECT GROUP_CONCAT(prodid SEPARATOR ', '),GROUP_CONCAT(quantity SEPARATOR ', '),userid
    FROM cart where Userid=5 GROUP BY userid;"
Mukesh Kalgude
  • 4,814
  • 2
  • 17
  • 32