0

I have a table named order where there is set a column name list

TABLE list
id |  list      | price    | date
---------------------------------------
1  | Cigar      |  5.00    | 2016-06-30
2  | Beer       |  6.00    | 2016-06-30
3  | Whiskey    |  20.00   | 2016-06-30
4  | Bacon      |  10.00   | 2016-06-30

I'd like to insert the list into another table named confirmation in a way that all of them could be in a same row! However, it doesn't work and is inserting in many rows!

The way I want

TABLE confirmation
id |            theorder             
--------------------------------
1  | Cigar, Beer, Whiskey, Bacon

The way is showing

TABLE confirmation
id |  theorder      
--------------
1  | Cigar,
2  | Beer,
3  | Whiskey,
4  | Bacon,

Here is the code: I'm working with foreach!

$sql     = "SELECT list FROM order";
$result  = $conn->query($sql);
$getList = $result->fetchAll(PDO::FETCH_ASSOC);

foreach($getOrder as $order) {
  $products = $order['theorder'] . ', ';
  $sql      = "INSERT INTO confirmation (theorder) VALUES ('$products')";
  $result   = $conn->query($sql);
}
Caio Ferrari
  • 319
  • 1
  • 3
  • 13
  • [Here](http://stackoverflow.com/questions/36781495/php-mysql-consolidate-column-where-other-column-has-duplicates) is similar question. – Wizard Jun 30 '16 at 00:51

1 Answers1

2

Every time you perform an INSERT query it creates a new row. Since you're doing this in a loop, it creates a new row for each product.

If you want to combine items, use GROUP_CONCAT:

INSERT INTO confirmation (theorder)
SELECT GROUP_CONCAT(list SEPARATOR ', ')
FROM `order`

Notice that you need to quote the table name order with backticks because it's a reserved word. It's generally best to avoid using reserved words as table and column names, since if you forget to quote it you'll get a confusing syntax error. See Syntax error due to using a reserved word as a table or column name in MySQL

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Right. This SQL query will do the whole thing. – Barmar Jun 30 '16 at 00:50
  • Thank you! I'll try and rate it soon! =D – Caio Ferrari Jun 30 '16 at 00:50
  • @CaioFerrari , I suspect you will need group by date. – Wizard Jun 30 '16 at 00:52
  • 1
    @Wizard I suspect so as well. But his original code doesn't filter by date, it just gets all the orders. – Barmar Jun 30 '16 at 00:53
  • @Barmar just a little question: how can I mix the answer you've typed with adding new values? Does exist something like this? `INSERT INTO confirmation (theorder, theprice, thedate) SELECT GROUP_CONCAT(list SEPARATOR ', ') VALUES ($theprice, $thedate) FROM 'order'` – Caio Ferrari Jun 30 '16 at 01:39
  • 1
    You can put literals in the `SELECT` list: `SELECT GROUP_CONCAT(list SEPARATOR ', '), '$theprice', '$thedate' FROM order` – Barmar Jun 30 '16 at 01:41